How do I resolve Promisse.all

Viewed 124

I have an array of promises that looks like this:

const content = await getData() //gets data from API
    const drinkURL =  content.drinks.map( item => "lookup.php?i=" + item.idDrink) // gets element in the API end-point
    const getInfo = async() => {
        let allPromises = Promise.all(drinkURL.map(item => getData(item)))  
        allPromises.catch(e => console.log(e)) // Trying to catch any errors here, but can't.
        return allPromises    
    }

I want to add a catch statement in case any of the promises can not resolve. I have tried writing it inside the getInfo function, and after the .then() inside the next snippet.

const view = `
        <div class="Drink-card">
            <a href="/">Home</a>
            ${await getInfo()
                .then(ele => ele.map(item => item.drinks.map( drink => `
            <article class="Drink-main">
                <img src="${drink.strDrinkThumb}" alt="${drink.strDrink}">
                <h2>${drink.strDrink}</h2>
            </article>
`)).join("")).catch(e => console.log(e))//Does not work in here either}

I have tried a bunch of ways but can't come up with a working result.

Thanks!

2 Answers

You should use await keyword (1) combines with catch inside of each promise (2) as the following simple sample :

enter image description here

Full code sample below:

function getData(object){
    return new Promise(resolve => {
        if(object.value === "3") 
            throw new Error("Whoops!") 
        else 
            resolve(object.value);
    });
}

var drinkURLs = [{ value: "1" }, { value: "2" }, { value: "3" }];
var getInfo = async() => {
    var promises =  drinkURLs.map(item => getData(item));
    var results = await Promise.all(promises.map(p => p.catch(e => e)));
    var inValidResults = results.filter(result => (result instanceof Error));
    var validResults = results.filter(result => !(result instanceof Error));
    console.log({inValidResults, validResults}); 

    return validResults;    
}

await getInfo();

You can use Promise.allSettled() function.

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise while Promise.all rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

Related