带有承诺的While循环 [英] While loop with promises
本文介绍了带有承诺的While循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用诺言做while循环之类的惯用方式是什么?所以:
What would be the idiomatic way to do something like a while loop with promises. So:
做点什么 如果情况仍然存在,再做一次 重复 然后再做些其他事情.
do something if the condition still stands do it again repeat then do something else.
dosomething.then(possilblydomoresomethings).then(finish)
我是用这种方式做的,我想知道是否还有更好/更理想的方式?
I've done it this way I was wondering if there were any better/more idomatic ways?
var q = require('q');
var index = 1;
var useless = function(){
var currentIndex = index;
console.log(currentIndex)
var deferred = q.defer();
setTimeout(function(){
if(currentIndex > 10)
deferred.resolve(false);
else deferred.resolve(true);
},500);
return deferred.promise;
}
var control = function(cont){
var deferred = q.defer();
if(cont){
index = index + 1;
useless().then(control).then(function(){
deferred.resolve();
});
}
else deferred.resolve();
return deferred.promise;
}
var chain = useless().then(control).then(function(){console.log('done')});
输出: 1个 2个 3 4 5 6 7 8 9 10 11 完成
Output: 1 2 3 4 5 6 7 8 9 10 11 done
推荐答案
我将使用一个对象包装该值.这样,您可以拥有一个done
属性,让循环知道您已完成.
I'd use an object to wrap the value. That way you can have a done
property to let the loop know you're done.
// fn should return an object like
// {
// done: false,
// value: foo
// }
function loop(promise, fn) {
return promise.then(fn).then(function (wrapper) {
return !wrapper.done ? loop(Q(wrapper.value), fn) : wrapper.value;
});
}
loop(Q.resolve(1), function (i) {
console.log(i);
return {
done: i > 10,
value: i++
};
}).done(function () {
console.log('done');
});
这篇关于带有承诺的While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文