最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to wait for promise on a map inside a loop? - Stack Overflow

programmeradmin2浏览0评论

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)
}

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)
}
Share asked Nov 25, 2021 at 8:46 RaneRane 1443 silver badges7 bronze badges 4
  • You can't await the map() (map isn't async/doesn't return a promise) but you can return an array full of promises from map and then await the Promise.all – pilchard Commented Nov 25, 2021 at 8:51
  • You can't await inside for loop. Consider using await for instead link – n1md7 Commented Nov 25, 2021 at 9:20
  • Does this answer your question? Best way to call an asynchronous function within map? – jonrsharpe Commented Nov 25, 2021 at 9:57
  • Partly. That question is for a promise in a map. My question is for a promise in a map in a for loop. – Rane Commented Nov 27, 2021 at 12:06
Add a ment  | 

3 Answers 3

Reset to default 6

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".

You can do something like this

let url = 'https://jsonplaceholder.typicode./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()

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);
}
发布评论

评论列表(0)

  1. 暂无评论