Wait until all promises complete even if some rejected

前端 未结 18 1907
醉酒成梦
醉酒成梦 2020-11-21 04:55

Let\'s say I have a set of Promises that are making network requests, of which one will fail:

// http://does-not-exist will throw a TypeError
va         


        
18条回答
  •  执笔经年
    2020-11-21 05:30

    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?

提交回复
热议问题