How to await asynchronous map function?


let me quickly get to the point. I have a function which fetches some user ids. It works very well.

const allIds = await fetchAllIds(someUrl);

Now the problem comes when I want to do something different. I’d like to loop over those ids and do some async await stuff with them. That is, to mainly fetch some data for each one with axios and modify them accordingly. (id) => {
  // 1. Fetch some data (try, catch and await)
  // 2. Modify the id based on that data
  // 3. Return the id, namely replace the old one

At the end of my code, I simply return allIds. The problem is that it returns them without waiting for the map function to execute completely. I tried different methods and none of it seems to be working. Could you please help me to make it work or perhaps suggest some other possible solutions? Thanks in advance!


Use this instead.

const newList = await Promise.all(>new Promise(async(res)=>{
 // do your async here and get result;

Answered By – noiseymur

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published