Promise resolution as soon as all internal concurrent promises resolved or rejected

I am looking for something similar to Promise.allthat that will continue to resolve promises at the same time even if one or more of the promises rejects or gives an error. Each request is independent of another request.

Close to what I want - see comments

function fetchRequest (request) {
  return new Promise(function (resolve, reject) {
    fetch(request)
    .then(function(response) {
      return response.text();      

    }).then(function (responseXML) {
      //Do something here. Maybe add data to dom
      resolve(responseXML);

    }).catch(function (err) {
      reject(new Error(err));
    }
}

function promiseRequests (requests) {
  var result = Promise.resolve();

  for (var i = 0; i < requests.length; i++) {
    result = fetchRequest(requests[i])
  }

  //This is wrong as it will resolve when the last promise in the requests array resolves
  // - not when all requests resolve
  resolve(result);
}

promiseRequests(['url1.com', 'url2.com']).then(function (data) {
  console.log('All requests finished');
  //optionally have data be an array of resolved and rejected promises
});

I managed to use Promise.allfetchRequest together with only the resolving promise, and this leads to the expected result (an array of results and undefined), but I feel that this is the wrong way to do something, It also removes my ability to use abandoned errors.

Works, but seems to be misusing permission

function fetchRequest (request) {
  return new Promise(function (resolve, reject) {
    fetch(request)
    .then(function(response) {
      return response.text();      

    }).then(function (responseXML) {
      resolve(responseXML);

    }).catch(function (err) {
      resolve();
    }
}

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

Please respond only to es6 API support.

0
2

Promise.all fetchRequest promises

. ES6 , allSettled (Q) settle (Bluebird 2.x) , Promise.all , . Bluebird .reflect() .

undefined , , .

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

. , :

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

:

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

 const promises = ['url1.com', 'url2.com'].map(fetch).map(swallow);
 Promise.all(promises).then(function (data) {
   // ...
 });
+4

Source: https://habr.com/ru/post/1662219/


All Articles