[javascript] Wait until all promises complete even if some rejected

Here's my custom settledPromiseAll()

const settledPromiseAll = function(promisesArray) {
  var savedError;

  const saveFirstError = function(error) {
    if (!savedError) savedError = error;
  };
  const handleErrors = function(value) {
    return Promise.resolve(value).catch(saveFirstError);
  };
  const allSettled = Promise.all(promisesArray.map(handleErrors));

  return allSettled.then(function(resolvedPromises) {
    if (savedError) throw savedError;
    return resolvedPromises;
  });
};

Compared to Promise.all

  • If all promises are resolved, it performs exactly as the standard one.

  • If one of more promises are rejected, it returns the first one rejected much the same as the standard one but unlike it waits for all promises to resolve/reject.

For the brave we could change Promise.all():

(function() {
  var stdAll = Promise.all;

  Promise.all = function(values, wait) {
    if(!wait)
      return stdAll.call(Promise, values);

    return settledPromiseAll(values);
  }
})();

CAREFUL. In general we never change built-ins, as it might break other unrelated JS libraries or clash with future changes to JS standards.

My settledPromiseall is backward compatible with Promise.all and extends its functionality.

People who are developing standards -- why not include this to a new Promise standard?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to promise

Axios handling errors typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here Syntax for async arrow function Angular 2: How to call a function after get a response from subscribe http.post How to use fetch in typescript Returning Promises from Vuex actions Use async await with Array.map Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai using setTimeout on promise chain Why is my asynchronous function returning Promise { <pending> } instead of a value?

Examples related to es6-promise

How to reject in async/await syntax? What is difference between Axios and Fetch? What is an unhandled promise rejection? JavaScript ES6 promise for loop Returning Promises from Vuex actions how to cancel/abort ajax request in axios Axios get access to response header fields How to pass parameter to a promise function Wait until all promises complete even if some rejected Handling errors in Promise.all