用诺言做诸如while循环之类的事情的惯用方式是什么。所以:
如果条件仍然存在,请执行某项操作,然后再次重复执行其他操作。
dosomething.then(possilblydomoresomethings).then(finish)
我这样做是想知道是否有更好/更理想的方法?
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完成