我一直在学习使用蓝鸟两周的承诺 . 我对他们大多了解,但我去解决一些相关的问题,似乎我的知识已经崩溃了 . 我正在尝试这个简单的代码:
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
-
面向蓝鸟的唯一答案是使用递归 . 这些看起来好像错了,那就好了!让我知道 .
-
唐't allow you to use result of the condition. Although this isn' t要求 - 我'm just curious if it'是可能的 . 代码I 'm writing, one use case needs it, the other doesn' t .
现在,有一个关于使用这个async()方法的RSVP的答案 . 真正令我困惑的是bluebird文档,我甚至在存储库中看到了 Promise.async()
调用的代码,但我在最新的bluebird副本中看不到它 . 它只在git存储库中还是什么?
1 回答
这并不是100%清楚你想要做什么,但我会写一个答案来做你提到的以下事情:
循环,直到满足代码中的某些条件
允许您在循环迭代之间使用延迟
允许您获取并处理最终结果
与Bluebird一起使用(我将代码符合ES6承诺标准,该标准将与Bluebird或本机承诺一起使用)
没有堆栈构建
首先,假设您有一些异步函数返回一个promise,其结果用于确定是否继续循环 .
现在,您希望循环,直到返回的值满足某些条件
如果你想让它更通用,那么你可以传递函数和比较,你可以这样做:
您尝试这样的结构:
无法工作,因为
getNextItem()
返回一个始终为!== false
的promise,因为promise是一个对象,因此无法工作 . 如果你想测试一个promise,你必须使用.then()
来获取它的值,你必须异步执行comparson所以你不能直接返回这样的值 .注意:虽然这些实现使用调用自身的函数,但这不会导致堆栈堆积,因为它们会异步调用自身 . 这意味着在函数再次调用自身之前,堆栈已经完全展开,因此没有堆栈构建 . 从
.then()
处理程序始终是这种情况,因为Promise规范要求在堆栈返回"platform code"之前不调用.then()
处理程序,这意味着它在调用.then()
处理程序之前已解除所有常规"user code" .Using async and await in ES7
在ES7中,您可以使用async并等待"pause"循环 . 这可以使这种类型的迭代更容易编码 . 这在结构上看起来更像是典型的同步循环 . 它使用
await
来等待promises,因为函数声明为async
,它总是返回一个promise: