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

javascript - How to wait all Promise are resolve in a loop? - Stack Overflow

programmeradmin2浏览0评论
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)
}

results is empty because the calls in the for are asynchronous and not yet executed.

How can I wait that all Promise in the for loop are resolved ?

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

results is empty because the calls in the for are asynchronous and not yet executed.

How can I wait that all Promise in the for loop are resolved ?

Share Improve this question asked Jan 19 at 14:57 Calim SnowCalim Snow 31 silver badge1 bronze badge 2
  • 3 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – ADyson Commented Jan 19 at 14:58
  • 3 Alternatively, Promise.allSettled to allow individual tasks to fail. – samthecodingman Commented Jan 19 at 15:20
Add a comment  | 

1 Answer 1

Reset to default 4

You can use Promise.all to your advantage. It will allow you to wait until an array of promises gets resolved.

Refer the below code for reference:

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

async function myFunction() {
  const params = [param1, param2, ...];
  const results = await Promise.all(params.map(param => getSomething(param))); // Use Promise.all get the results in order
  console.log(results);
}

发布评论

评论列表(0)

  1. 暂无评论