user9042204
user9042204

Reputation: 11

Why can't using "await" for each mapped element in an array of promises be used instead of "promise.all"?

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.

Upvotes: 0

Views: 35

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Remember that an async function always returns a promise.

In your version that doesn't work, you're awaiting the result of map, but there's no reason to do that, because map returns an array, not a promise. The array contains the promises from the calls to the async callback you provided map, but they're still pending since nothing has waited for them to settle (map knows nothing about promises). Your code within the async callback waits for the promises from fetch to settle before settling the async callback's promise, but nothing waits for the promise from the async callbacks 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).

Upvotes: 1

Related Questions