ES6 Promises/calling a function after multiple promises are fulfilled (can't use Promises.all) [duplicate]

浪尽此生 提交于 2019-12-21 05:25:28

问题


I'm writing Javascript which needs these events to happen in this order:

  1. Fire off several API calls simultaneously
  2. Once all calls have completed and responses have returned, execute a line of code

Sounds simple but the tricky part is that I can't use Promises.all() because I still want that line of code to execute after all promises have been fulfilled, successful or not. Unless I misunderstand Promises.all(), one failing would cause the line of code to not execute in then() and execute too soon in error().

I very well might be missing something obvious but the only other way I can see would be to chain the API call promises together but that would result in not firing them all at once. So basically I think I need a version of Promises.all() that isn't "fail-fast".

What's the proper way to do this?


回答1:


To do it strictly using ES6 promises, you will need to wrap each promise in another wrapper promise, which gets resolved when the wrapped promise is fulfilled or rejected.

You can do that like this:

Promise.all( 
  promises.map( promise => Promise.resolve( promise ).catch( _=>_ ) )
).then ( function ( ) {
    // All promises finished
} );

This assumes that promises is an array of promises and/or values.




回答2:


There's probably a slicker way than this, and even a better written version of this particular approach, but instead of using Promise.all, you could just chain behavior to each promise (for both then and catch, so it doesn't matter) that updates a value in a master Promise.

const allPromises = arrayOfPromises => Promise((resolve,reject)=> {
  const ln = arrayOfPromises.length,
        done = 0;

  const allDone => _ => {
    if(++done===ln){ resolve(); }
  }
  arrayOfPromises.map(p=>p.then(allDone).catch(allDone));
});


来源:https://stackoverflow.com/questions/36923225/es6-promises-calling-a-function-after-multiple-promises-are-fulfilled-cant-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!