【发布时间】:2016-08-26 14:34:22
【问题描述】:
我已经使用 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:
Correct way to write loops for promise.
但接受的答案,以及其他答案:
- 面向 Q.js 或 RSVP
- 针对蓝鸟的唯一答案是使用递归。这些似乎很可能在像我这样的无限循环中导致巨大的堆栈溢出?或者充其量,是非常低效的并且白白地创建一个非常大的堆栈?如果我错了,那好吧!告诉我。
- 不允许您使用条件的结果。虽然这不是必需的——我只是好奇它是否可能。我正在编写的代码,一个用例需要它,另一个不需要。
现在,有一个关于使用此 async() 方法的 RSVP 的答案。真正让我感到困惑的是 bluebird 文档,我什至在存储库中看到了 Promise.async() 调用的代码,但我在最新的 bluebird 副本中没有看到它。它只是在 git 存储库中还是在什么地方?
【问题讨论】:
-
呃,您链接到的解决方案确实使用了
Promise.method,它是针对 Bluebird 而不是 Q?但如果你想要别的东西,看看here。 -
如果你坚持的话,你可以使用 Bluebird 的
Promise.coroutine和while循环 :-) 这就是RSVP.Promise.async所做的。 -
There's nothing wrong with recursion,毕竟这是异步环境中唯一可行的方法。不确定这是否是回答您的主要问题的有效副本。
-
我不确定您所说的“不允许您使用条件结果”是什么意思。如果条件为
true,则执行你的body,如果为false,则退出循环;你还想用什么作为“结果”? -
仅供参考,从异步回调调用您自己的函数不会导致堆栈堆积。调用异步回调时,堆栈已经展开。
标签: javascript promise bluebird