【发布时间】:2016-01-20 00:21:16
【问题描述】:
我怎么能一个接一个地兑现承诺?
waitFor(t),是一个函数,它返回一个在t 时间之后解析的承诺。我希望能够做到的是:
waitFor(1000) Then when finished, console.log('Finished wait of 1000 millis') then
waitFor(2000) Then when finished, console.log('Finished wait of 2000 millis') then
waitFor(3000) Then when finished, console.log('Finished wait of 3000 millis')
这是我尝试过的:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve);
}).then(waitFor(2000).then(function(resolve, reject) {
console.log(resolve);
})).then(waitFor(3000).then(function(resolve, reject) {
console.log(resolve);
}));
不幸的是,这个 console.logs 每隔 1 秒记录一次语句,这意味着所有的 Promise 都是一次调用的。
我设法通过这样的回调解决了这个问题,但这让一切变得非常丑陋:
waitFor(1000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
waitFor(2000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
waitFor(3000).then(function(resolve, reject) {
console.log(resolve+' @ '+(new Date().getSeconds()));
});
});
});
那么我应该如何使用可以使它工作的承诺来做到这一点,而不是使用丑陋的回调地狱?
【问题讨论】:
-
我什至没有使用 angularjs....
-
我指向博客以获得一个想法 - 使用递归函数,它将遍历您的一系列承诺。
标签: javascript node.js callback promise