如何循环等待所有Promise被解析?

问题描述 投票:0回答:1
async function getSomething(parameter) {
  ...
}

function myFunction() {
  const params = [param1, param2, ...]
  const results = []
  let i = 0

  params.forEach((param) => {
    getSomething(param).then((result) => results[i++] = result)
  })
  
  console.log(results)
}

结果为空,因为 for 中的调用是异步的,尚未执行。

如何等待for循环中的所有Promise都被解决?

javascript node.js
1个回答
0
投票

您可以利用

Promise.all
对您有利。它将允许您等待一系列承诺得到解决。

参考以下代码:

async function getSomething(parameter) {
  // Your business logic here
}

async function myFunction() {
  const params = [param1, param2, ...];
  const results = [];
  const promises = params.map(async (param) => { // Generate a array of promises
    const result = await getSomething(param);
    results.push(result);
  });
  await Promise.all(promises); // Wait all the promises in the array to get resolved
  console.log(results); // Output after all promises gets resolved
}

© www.soinside.com 2019 - 2024. All rights reserved.