bluebird promise的while()循环正确(无递归?)

Proper while() loop for bluebird promises (without recursion?)

本文关键字:递归 循环 while promise bluebird      更新时间:2023-09-26

我已经用bluebird学习promise两周了。我已经基本理解了,但我去解决了一些相关的问题,似乎我的知识已经分崩离析了。我正在尝试做这个简单的代码:

var someGlobal = true;
whilePromsie(function() { 
   return someGlobal;
}, function(result) { // possibly even use return value of 1st parm?
 // keep running this promise code
 return new Promise(....).then(....);
});

作为一个具体的例子:

// This is some very contrived functionality, but let's pretend this is 
// doing something external: ajax call, db call, filesystem call, etc.
// Simply return a number between  0-999 after a 0-999 millisecond
// fake delay.
function getNextItem() { 
    return new Promise.delay(Math.random()*1000).then(function() {
        Promise.cast(Math.floor(Math.random() * 1000));
    });
}
promiseWhile(function() {
    // this will never return false in my example so run forever
    return getNextItem() !== false;
}, // how to have result == return value of getNextItem()? 
function(result) {
    result.then(function(x) { 
        // do some work ... 
    }).catch(function(err) { 
        console.warn("A nasty error occured!: ", err);
    });
}).then(function(result) { 
    console.log("The while finally ended!");
});

现在我已经完成了作业!这里也有同样的问题,但针对Q.js:

为promise编写循环的正确方式。

但公认的答案,以及其他答案:

  • 面向Q.js或RSVP
  • 唯一针对蓝鸟的答案是递归。这些似乎很可能会在像我这样的无限循环中导致巨大的堆栈溢出?或者充其量,效率很低,免费创建一个很大的堆栈?如果我错了,那就好了!让我知道
  • 不允许您使用条件的结果。虽然这不是要求,但我只是好奇这是否可能。我正在编写的代码,一个用例需要它,另一个不需要

现在,有一个关于使用此async()方法的RSVP的答案。真正让我困惑的是bluebird文档,我甚至在存储库中看到了Promise.async()调用的代码,但在我最新的bluebird副本中没有看到。它只是在git存储库中还是其他什么?

你想做什么还不是100%清楚,但我会写一个答案,做你提到的以下事情:

  1. 循环直到满足代码中的某些条件
  2. 允许您在循环迭代之间使用延迟
  3. 允许您获取和处理最终结果
  4. 适用于Bluebird(我将按照ES6 promise标准进行编码,该标准将适用于Bluebird或原生promise)
  5. 没有堆积

首先,假设您有一个异步函数,它返回一个promise,其结果用于确定是否继续循环。

function getNextItem() {
   return new Promise.delay(Math.random()*1000).then(function() {
        return(Math.floor(Math.random() * 1000));
   });
}

现在,您想要循环,直到返回的值满足某种条件

function processLoop(delay) {
    return new Promise(function(resolve, reject) {
        var results = [];
        function next() {
            getNextItem().then(function(val) {
                // add to result array
                results.push(val);
                if (val < 100) {
                    // found a val < 100, so be done with the loop
                    resolve(results);
                } else {
                    // run another iteration of the loop after delay
                    setTimeout(next, delay);
                }
            }, reject);
        }
        // start first iteration of the loop
        next();
    });
}
processLoop(100).then(function(results) {
   // process results here
}, function(err) {
   // error here
});

如果你想让它更通用,这样你就可以传递函数和比较,你可以这样做:

function processLoop(mainFn, compareFn, delay) {
    return new Promise(function(resolve, reject) {
        var results = [];
        function next() {
            mainFn().then(function(val) {
                // add to result array
                results.push(val);
                if (compareFn(val))
                    // found a val < 100, so be done with the loop
                    resolve(results);
                } else {
                    // run another iteration of the loop after delay
                    if (delay) {
                        setTimeout(next, delay);
                    } else {
                        next();
                    }
                }
            }, reject);
        }
        // start first iteration of the loop
        next();
    });
}
processLoop(getNextItem, function(val) {
    return val < 100;
}, 100).then(function(results) {
   // process results here
}, function(err) {
   // error here
});

你尝试这样的结构:

return getNextItem() !== false;

无法工作,因为getNextItem()返回一个始终为!== false的promise,因为promise是一个无法工作的对象。如果你想测试一个promise,你必须使用.then()来获得它的值,并且你必须异步地进行比较,这样你就不能直接返回这样的值。


注意:虽然这些实现使用了一个调用自己的函数,但这不会导致堆栈堆积,因为它们是异步调用自己的。这意味着在函数再次调用自己之前,堆栈已经完全展开,因此没有堆栈堆积。.then()处理程序总是这样,因为Promise规范要求在堆栈返回到"平台代码"之前不调用.then()处理程序,这意味着在调用.then()处理程序之前,它已经展开了所有常规的"用户代码"。


在ES7中使用asyncawait

在ES7中,您可以使用async和wait来"暂停"循环。这可以使这种类型的迭代的代码更加简单。这在结构上看起来更像一个典型的同步环路。它使用await来等待promise,因为函数被声明为async,所以它总是返回一个promise:

function delay(t) {
    return new Promise(resolve => {
        setTimeout(resolve, t);
    });
}
async function processLoop(mainFn, compareFn, timeDelay) {
    var results = [];
    // loop until condition is met
    while (true) {
        let val = await mainFn();
        results.push(val);
        if (compareFn(val)) {
            return results;
        } else {
            if (timeDelay) {
                await delay(timeDelay);
            }
        }
    }
}
processLoop(getNextItem, function(val) {
    return val < 100;
}, 100).then(function(results) {
   // process results here
}, function(err) {
   // error here
});