While 循环使用 bluebird promises

While loop using bluebird promises

我正在尝试使用 promises 实现 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可以翻译成resolvedefer 应该 indeed not be used.

您只能通过将 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 都可以 return 承诺。对于类似的实现,还可以查看 Correct way to write loops for promise. Closer to your original function would be

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:循环条件为 returns 总和:

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