How to early break reduce() method?

后端 未结 12 1210
忘掉有多难
忘掉有多难 2020-11-28 05:44

How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <=         


        
12条回答
  •  日久生厌
    2020-11-28 06:42

    If you want to chain promises sequentially with reduce using the pattern below:

    return [1,2,3,4].reduce(function(promise,n,i,arr){
       return promise.then(function(){
           // this code is executed when the reduce loop is terminated,
           // so truncating arr here or in the call below does not works
           return somethingReturningAPromise(n);
       });
    }, Promise.resolve());
    

    But need to break according to something happening inside or outside a promise things become a little bit more complicated because the reduce loop is terminated before the first promise is executed, making truncating the array in the promise callbacks useless, I ended up with this implementation:

    function reduce(array, promise, fn, i) {
      i=i||0;
      return promise
      .then(function(){
        return fn(promise,array[i]);
      })
      .then(function(result){
        if (!promise.break && ++i

    Then you can do something like this:

    var promise=Promise.resolve();
    reduce([1,2,3,4],promise,function(promise,val){
      return iter(promise, val);
    }).catch(console.error);
    
    function iter(promise, val) {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          if (promise.break) return reject('break');
          console.log(val);
          if (val==3) {promise.break=true;}
          resolve(val);
        }, 4000-1000*val);
      });
    }
    

提交回复
热议问题