Wait until all promises complete even if some rejected

前端 未结 18 1958
醉酒成梦
醉酒成梦 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:40

    I really like Benjamin's answer, and how he basically turns all promises into always-resolving-but-sometimes-with-error-as-a-result ones. :)
    Here's my attempt at your request just in case you were looking for alternatives. This method simply treats errors as valid results, and is coded similar to Promise.all otherwise:

    Promise.settle = function(promises) {
      var results = [];
      var done = promises.length;
    
      return new Promise(function(resolve) {
        function tryResolve(i, v) {
          results[i] = v;
          done = done - 1;
          if (done == 0)
            resolve(results);
        }
    
        for (var i=0; i

提交回复
热议问题