How to Use async/await inside map() in JavaScript


I recently needed to use async/await inside a map function.

Suppose I have a list of ids, and I want to make an API call on each id.

const ids = ["id_1", "id_2", "id_3"];
const dataById = ids.map((id) => {
  // make API call
});

API calls are generally asynchronous, so the natural progression would be to make the function passed into map() an async function.

const ids = ["id_1", "id_2", "id_3"];
const dataById = ids.map(async (id) => {
  const data = await getDataById(id);
  return { id, data };
});

Unfortunately, making the map() function asynchronous means that map() will return an array of promises.

[Promise {<pending>}, Promise {<pending>}, Promise {<pending>}]

In order to retrieve the results of all the promises, we can use Promise.all().

We can return Promise.all() on the array of promises.

Promise.all(dataById);

Notice, however, that Promise.all() itself will return a promise, so we can await the result of this line.

await Promise.all(dataById);