而循环使用蓝鸟承诺

While loop using bluebird promises

本文关键字:蓝鸟 承诺 循环      更新时间:2023-09-26

我正在尝试使用promise实现while循环。

这里概述的方法似乎奏效了。http://blog.victorquinn.com/javascript-promise-while-loop它使用类似的功能

var Promise = require('bluebird');
var promiseWhile = function(condition, action) {
    var resolver = Promise.defer();
    var loop = function() {
        if (!condition()) return resolver.resolve();
        return Promise.cast(action())
            .then(loop)
            .catch(resolver.reject);
    };
    process.nextTick(loop);
    return resolver.promise;
};

这似乎使用了反模式和不推荐使用的方法,如cast和defer。

有人知道更好或更现代的方法来实现这一点吗?

感谢

cast可以转换为resolve。确实不应该使用defer

您只能通过将then调用链接并嵌套到初始Promise.resolve(undefined)上来创建循环。

function promiseWhile(predicate, action, value) {
    return Promise.resolve(value).then(predicate).then(function(condition) {
        if (condition)
            return promiseWhile(predicate, action, action());
    });
}

这里,predicateaction都可以返回promise。对于类似的实现,还可以看看编写promise循环的正确方法。将更接近您的原始功能

function promiseWhile(predicate, action) {
    function loop() {
        if (!predicate()) return;
        return Promise.resolve(action()).then(loop);
    }
    return Promise.resolve().then(loop);
}

我更喜欢这种实现,因为它更容易模拟中断并继续使用:

var Continue = {}; // empty object serves as unique value
var again = _ => Continue;
var repeat = fn => Promise.try(fn, again)
  .then(val => val === Continue && repeat(fn) || val);

示例1:当源或目的地指示错误时停止

repeat(again => 
    source.read()
    .then(data => destination.write(data))
    .then(again)

示例2:如果给定90%概率的硬币翻转结果为0 ,则随机停止

var blah = repeat(again =>
    Promise.delay(1000)
    .then(_ => console.log("Hello"))
    .then(_ => flipCoin(0.9) && again() || "blah"));

示例3:带有返回总和的条件的循环:

repeat(again => {
  if (sum < 100) 
    return fetchValue()
      .then(val => sum += val)
      .then(again));
  else return sum;
})