【发布时间】:2015-03-23 22:19:50
【问题描述】:
我正在尝试使用本机 ES6 promises 创建一个异步循环,它有点可以工作,但不正确。我想我在某个地方犯了一个大错误,我需要有人告诉我它在哪里以及它是如何正确完成的
var i = 0;
//creates sample resolver
function payloadGenerator(){
return function(resolve) {
setTimeout(function(){
i++;
resolve();
}, 300)
}
}
// creates resolver that fulfills the promise if condition is false, otherwise rejects the promise.
// Used only for routing purpose
function controller(condition){
return function(resolve, reject) {
console.log('i =', i);
condition ? reject('fin') : resolve();
}
}
// creates resolver that ties payload and controller together
// When controller rejects its promise, main fulfills its thus exiting the loop
function main(){
return function(resolve, reject) {
return new Promise(payloadGenerator())
.then(function(){
return new Promise(controller(i>6))
})
.then(main(),function (err) {
console.log(err);
resolve(err)
})
.catch(function (err) {
console.log(err , 'caught');
resolve(err)
})
}
}
new Promise(main())
.catch(function(err){
console.log('caught', err);
})
.then(function(){
console.log('exit');
process.exit()
});
现在输出:
/usr/local/bin/iojs test.js
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
fin
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
error: [TypeError: undefined is not a function]
caught [TypeError: undefined is not a function]
exit
Process finished with exit code 0
好的部分:它到达了终点。
不好的部分:它捕获了一些错误,我不知道为什么。
【问题讨论】:
-
不管你使用 promises 的方式使用库是真的奇怪。你在这里的最终目标是什么?你想用 Promise 实现一个“while”吗?
-
.then(main(),function (err) {。main()什么时候在那里? -
你忘了告诉我们这段代码应该做什么。
-
@BenjaminGruenbaum 是的,我知道。我是新的承诺,并试图弄清楚它们是如何工作的。是的,这是一个while循环; JLRishe:它应该数到 7 并且不会产生任何错误
标签: javascript node.js ecmascript-6 promise es6-promise