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

后端 未结 5 1374
隐瞒了意图╮
隐瞒了意图╮ 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:28

    Don't use Promise.all! That fails the entire operation if any one of your promises fails!

    Unless you're okay with that prospect, you'd be way better off doing something like this:

    function sleep(ms) {
      return new Promise((resolve, reject) => {
        console.log(`starting ${ms}`);
        setTimeout(() => {
          if (ms > 1000) {
            console.log(`Threw out ${ms} because it took too long!`);
            reject(ms);
          } else {
            console.log(`done ${ms}`);
            resolve(ms);
          }
        }, ms);
      });
    }
    
    (async () => {
      console.log('aPromise, bPromise, cPromise executed concurrently as promises are in an array');
      const start = new Date();
      const aPromise = sleep(2000);
      const bPromise = sleep(500);
      const cPromise = sleep(5);
      
      try {
        const [a, b, c] = [await aPromise, await bPromise, await cPromise];
        // The code below this line will only run when all 3 promises are fulfilled:
        console.log(`slept well - got ${a} ${b} ${c} in ${new Date()-start}ms`);
      } catch (err) {
        console.log(`slept rough in ${err}ms`);
      }
    })();

提交回复
热议问题