Correct way to write loops for promise.

后端 未结 13 1928
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  天命终不由人
    2020-11-22 15:35

    Bergi's suggested function is really nice:

    var promiseWhile = Promise.method(function(condition, action) {
          if (!condition()) return;
        return action().then(promiseWhile.bind(null, condition, action));
    });
    

    Still I want to make a tiny addition, which makes sense, when using promises:

    var promiseWhile = Promise.method(function(condition, action, lastValue) {
      if (!condition()) return lastValue;
      return action().then(promiseWhile.bind(null, condition, action));
    });
    

    This way the while loop can be embedded into a promise chain and resolves with lastValue (also if the action() is never run). See example:

    var count = 10;
    util.promiseWhile(
      function condition() {
        return count > 0;
      },
      function action() {
        return new Promise(function(resolve, reject) {
          count = count - 1;
          resolve(count)
        })
      },
      count)
    

提交回复
热议问题