Resolve a promise once all internal concurrent promises have resolved or rejected

左心房为你撑大大i 提交于 2019-11-28 14:49:37

I have succeeded in using Promise.all together with only ever resolving the fetchRequest promises

That's basically the way to go. ES6 does not have a helper function like allSettled (Q) or settle (Bluebird 2.x) for this case, so we will need to use Promise.all similar to like you did. Bluebird even has a dedicated .reflect() utility for this.

You would however not resolve them with undefined in the case of a rejection, but rather with some useful value that allows to identify the errors.

function promiseRequests(requests) {
  return Promise.all(requests.map(request => {
    return fetch(request).then(res => {
      return {value:res};
    }, err => {
      return {reason:err};
    });
  }));
}

You are essentially asking for a way to swallow any errors. As such, a function like this will be your best bet:

function swallow(p) {
  // transforms rejected promises into promises fulfilled with undefined
  return p.catch(function () { });
}

You would use it as follows:

Promise.all([swallow(fetch('url1.com')), swallow(fetch('url2.com'))]).then(function (data) {
  console.log('All requests finished', data); //data could be ['resultXML', undefined]
});

or even

 const promises = ['url1.com', 'url2.com'].map(fetch).map(swallow);
 Promise.all(promises).then(function (data) {
   // ...
 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!