I have an array of fetch API calls that have been resolved as shown below:
let results = await Promise.all(promises);
I'm trying to get the result of each resolved fetch API call in the array. I tried console logging the results expecting the resolved responses
const newStuff = await results.map(async (response) => {
try {
const recipeDetail = await response.json();
return recipeDetail;
} catch (err) {
console.log("error1: ", err);
}
})
console.log(newStuff);
But I get back an array of pending promises.
However this below seems to work.
const newStuff = await Promise.all(results.map(async response => {
let recipeDetail = await response.json();
return recipeDetail;
}));
console.log(newStuff);
Why does the second example work when the first one doesn't?
Thanks in advance.
Remember that an
asyncfunction always returns a promise.In your version that doesn't work, you're
awaiting the result ofmap, but there's no reason to do that, becausemapreturns an array, not a promise. The array contains the promises from the calls to theasynccallback you providedmap, but they're still pending since nothing has waited for them to settle (mapknows nothing about promises). Your code within theasynccallback waits for the promises fromfetchto settle before settling theasynccallback's promise, but nothing waits for the promise from theasynccallbacks to setting.That's the purpose of
Promise.all: It waits for the promises to settle and fulfills its promise with an array of the fulfillment values (not an array of promises).