How to return accumulated returned Promise values as array to .then() following Array.prototype.reduce()?

后端 未结 3 517
梦毁少年i
梦毁少年i 2020-12-22 15:28

Given this pattern

someArray.reduce(function(p, item) {
  return p.then(function() {
    return someFunction(item);
  });
}, $.Deferred().resolve()).then(fun         


        
3条回答
  •  失恋的感觉
    2020-12-22 16:13

    There are multiple possible strategies depending upon the specifics of what you're trying to do: Here's one option:

    someArray.reduce(function(p, item) {
      return p.then(function(array) {
        return someFunction(item).then(function(val) {
            array.push(val);
            return array;
        });
      });
    }, $.Deferred().resolve([])).then(function(array) {
      // all done here
      // accumulated results in array
    }, function(err) {
      // err is the error from the rejected promise that stopped the chain of execution
    });
    

    Working demo: http://jsfiddle.net/jfriend00/d4q1aaa0/


    FYI, the Bluebird Promise library (which is what I generally use) has .mapSeries() which is built for this pattern:

    var someArray = [1,2,3,4];
    
    Promise.mapSeries(someArray, function(item) {
        return someFunction(item);
    }).then(function(results) {
        log(results);
    });
    

    Working demo: http://jsfiddle.net/jfriend00/7fm3wv7j/

提交回复
热议问题