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

后端 未结 2 1759
青春惊慌失措
青春惊慌失措 2020-12-12 03:26

I am looking for something similar to Promise.all that will continue to resolve promises concurrently even in the event that one or more of the promises reject

2条回答
  •  醉话见心
    2020-12-12 03:55

    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) {
       // ...
     });
    

提交回复
热议问题