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

后端 未结 3 524
梦毁少年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 15:53

    One solution possible :

    var $j = function(val, space) {
      return JSON.stringify(val, null, space || '')
    }
    var log = function(val) {
      document.body.insertAdjacentHTML('beforeend', '
    ' + val + '
    ') } 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 , ' ' )) });

提交回复
热议问题