Tôi đang cố gắng tạo vòng lặp không đồng bộ với kiểu gốc ES6 promises Nó loại hoạt động nhưng không chính xác. Tôi cho rằng tôi đã phạm sai lầm lớn ở đâu đó và tôi cần một ai đó cho tôi biết nó ở đâu và làm thế nào nó được thực hiện một cách chính xácVòng lặp với lời hứa gốc;
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()
});
Bây giờ kết quả:
/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
Phần tốt: đi đến cuối đường.
Phần xấu: nó bắt được một số lỗi và tôi không biết tại sao.
Bất kể thư viện nào được sử dụng theo cách bạn đang sử dụng lời hứa là _really_ lạ. Mục tiêu cuối cùng của bạn ở đây là gì? Bạn muốn thực hiện một "trong khi" với lời hứa? –
'.then (main(), function (err) {'. Khi nào 'main()' đang làm ở đó? –
Bạn quên nói cho chúng ta biết mã này được cho là làm gì. – JLRishe