【问题标题】:How to wait for promise on a map inside a loop?如何在循环内的地图上等待承诺?
【发布时间】:2022-01-03 13:19:07
【问题描述】:

我已经阅读了地图的承诺,但如果地图在函数内部,我似乎不知道如何实现它。

例如:

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

但是,我有这段代码,其中地图位于 for 循环内。

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

【问题讨论】:

  • 你不能等待map()(map 不是异步的/不返回一个promise)但是你可以从map 中返回一个充满promise 的数组,然后await这个Promise。全部
  • 你不能在 for 循环中 await。考虑使用await for 而不是link
  • 部分。这个问题是针对地图中的承诺。我的问题是 for 循环中的地图中的承诺。

标签: javascript node.js


【解决方案1】:

.map 中的异步代码不能控制,句号。

await所有你可以做的承诺

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

这读作“映射到承诺,然后等待所有承诺”。

【讨论】:

    【解决方案2】:

    你可以这样做

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

    【讨论】:

      【解决方案3】:

      如果您对 Axios 的请求取决于 map 函数中另一个请求的响应,@joegomain 建议的答案是一种有效的方法

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

      【讨论】:

        猜你喜欢
        • 2017-12-16
        • 2022-12-08
        • 2019-04-26
        • 1970-01-01
        • 2020-05-15
        • 2016-04-13
        • 2017-11-01
        • 1970-01-01
        • 2015-11-13
        相关资源
        最近更新 更多