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

荒凉一梦 提交于 2019-12-03 17:26:38

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.

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