How do I return the accumulated results of multiple (parallel) asynchronous function calls in a loop?

后端 未结 5 1377
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 09:14

I have a function foo which makes multiple (parallel) asynchronous calls in a loop. I need to somehow wait until the results of all of the calls are available.

5条回答
  •  伪装坚强ぢ
    2020-11-29 09:29

    As other answers mentioned, Promises are a good way to go. Promise.all() was mentioned in one but that one returns and rejects immediately if one of the promises fails.

    Promise.allSettled() is a good option if you want it to return only when ALL the promises are completed. This allows for handling if some promises were fulfilled while others were rejected.

    Here's a sample from the Mozilla docs:

    Promise.allSettled([
      Promise.resolve(33),
      new Promise(resolve => setTimeout(() => resolve(66), 0)),
      99,
      Promise.reject(new Error('an error'))
    ])
    .then(values => console.log(values));
    
    // [
    //   {status: "fulfilled", value: 33},
    //   {status: "fulfilled", value: 66},
    //   {status: "fulfilled", value: 99},
    //   {status: "rejected",  reason: Error: an error}
    // ]
    

提交回复
热议问题