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

老子叫甜甜 提交于 2019-11-28 14:19:35

问题


Given this pattern

someArray.reduce(function(p, item) {
  return p.then(function() {
    return someFunction(item);
  });
}, $.Deferred().resolve()).then(function() {
  // all done here
  // access accumulated fulfilled , rejected `Promise` values
}, function err() {

});

what approaches are possible to return accumulated values of fulfilled , rejected Promise objects to .then(fulfilled) as an array following call to .reduce() ?

function someFunction(index) {
  console.log("someFunction called, index = " + index);
  var $deferred = $.Deferred();

  window.setTimeout(function() {
    $deferred.resolve();
  }, 2000);

  return $deferred.promise();
}
   
var someArray = [1,2,3,4,5];

someArray.reduce(function(p, item) {
  return p.then(function() {
    return someFunction(item);
  });
}, $.Deferred().resolve()).then(function(data) {
  // all done here
  console.log(data, arguments) // `undefined` , `[]`
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

回答1:


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/




回答2:


One solution possible :

var $j = function(val, space) {
  return JSON.stringify(val, null, space || '')
}
var log = function(val) {
  document.body.insertAdjacentHTML('beforeend', '<div><pre>' + val + '</div></pre>')
}

var async = function(cur){
  var pro = new Promise(function(resolve, reject) {

        log('loading : ' + cur.name);
        
        // we simualate the loading
        setTimeout(function() {
          if(cur.name === 'file_3.js'){
            reject(cur.name);
          }
          resolve(cur.name);
        }, 1 * 1000);

      });

      return pro;
}

var files = '12345'.split('').map(function(v) {
  return {
    name: 'file_' + v + '.js', 
  }
});


var listed = files.reduce(function(t,v){

  t.p = t.p.then( function(){
    return async( v )
      .then(function(rep){
      
               t.fulfilled.push(rep);
               log('fulfilled :' + rep); 
               return rep;
      
      } , function(rep){
               
               t.rejected.push(rep);
               log('-----| rejected :' + rep); 
               return rep;
      }
   ).then(function(val){ t.treated.push(val) })
  });
  
  return t;
  
} , {p : Promise.resolve() , treated : [] , fulfilled : [] , rejected : [] } )


listed.p.then( function(){ 
  log( 'listed : ' + $j( listed , '   ' )) 
});



回答3:


Next to the approach demonstrated by @jfriend00, where you resolve each promise with an array where you append the current to all previous results, you can also use an array of promises as is known from the parallel execution pattern with Promise.all and .map.

For this, you have to put all the promises you create within the reduce steps in an array. After that, you can call Promise.all on this array to await all the results. The advantage of this approach is that your code only needs minimal adjustment, so that you can easily switch back and forth between a version that needs the results and one that does not.
To collect the results of each step in an array, we use a variant of reduce that is known as scan and does return an array (like map) instead of the latest result:

Array.prototype.scan = function scanArray(callback, accumulator) {
    "use strict";
    if (this == null) throw new TypeError('Array::scan called on null or undefined');
    if (typeof callback !== 'function') throw new TypeError(callback+' is not a function');

    var arr = Object(this),
        len = arr.length >>> 0,
        res = [];
    for (var k = 0; k < len; k++)
        if (k in arr)
            res[k] = accumulator = callback(accumulator, arr[k], k, arr);
    return res;
};

The pattern now looks like

Promise.all(someArray.scan(function(p, item) {
    return p.then(function() {
       return someFunction(item);
    });
}, Promise.resolve())).then(…)

(For jQuery, substitute Promise.resolve by $.Deferred().resolve() and Promise.all by $.when.apply($, …))



来源:https://stackoverflow.com/questions/33688342/how-to-return-accumulated-returned-promise-values-as-array-to-then-following

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!