Home > Blockchain >  How to wait for promise on a map inside a loop?
How to wait for promise on a map inside a loop?

Time:11-26

I've read of promises for maps but I can't seem to know how to implement it if the map is inside a function.

for Example:

async function1(){
  await mongoose.connect(CONNECTION_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  const account = await Account.find({
    priority: { $lt: 50000 },
  }).skip(i * 1000).limit(1000).sort("priority");

  const promise1 = await account.map(async (item) => {
    //make axios requests here
  }

  Promise.allSettled(promise1).then(()=> process.exit(0))
}

However, I have this code wherein the map is inside a for loop.

async function1(){
  await mongoose.connect(CONNECTION_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  //axios requests
  for (let i=0; i<50; i  ){
    const account = await Account.find({
      priority: { $lt: 50000 },
    })
      .skip(i * 1000)
      .limit(1000)
      .sort("priority");

    await account.map(async (item) => {
      //make axios requests here
    }
  }

  //should wait for the map inside the loop to finish before executing
  process.exit(0)
}

CodePudding user response:

You can not control asynchronous code in .map, period.

To await all promises you can do

  await Promise.all(account.map(async () => {
    // do your async thing
  }));

This reads "map to promises, then await all of them".

CodePudding user response:

You can do something like this

let url = 'https://jsonplaceholder.typicode.com/posts/'

async function getAll(){
    
    for(let i=0;i<5;i  ){
        await Promise.all([...Array(5)].map(async (_,j) => {
            const res = await fetch(url i ' ' j)
            console.log(i,j,res.data);
        }));
        console.log("End of i loop index ",i);
    }
    
}
getAll()
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The answer suggested by @joegomain is an effective way if in case your request to Axios depends on the response of another request in the map function

account.map(async (item) => {
  const { data } = await axios('/endpoint', options);
}
  • Related