我正在尝试执行以下操作:
我有一个函数looper()
,它根据条件调用自身。
我希望其中的某些部分仅执行一次,而其他部分则在每次调用时执行。
我不知道这是否是最好的方法,但我想不出其他方法,这不起作用。
var stopper = 3;
looper().then(function() {
console.log('This should happen only once');
});
function looper(d) {
if (!d)
var d = when.defer(); // recycled promise
console.log('This should happen EVERY time looper() is called');
next();
console.log('This shouldn’t happen if looper() is called again by next().');
function next() {
if (--stopper <= 0) {
d.resolve();
} else {
looper(d)
// if only next() could return a `return`
// so that looper() returns/exits based on this if condition ...
// return return
}
}
return d.promise;
}
有什么办法可以实现这个目标吗?
最佳答案
这里了解两件事很重要:
- Promises/A+ 递归地展开,以便您可以从处理程序返回复合 Promise。
- promise 链。当您已经使用 Promise 时,很少有需要延迟对象的情况。
一旦我们理解了这两件事,我们就可以创建一个更简单的“循环”,因为我们可以简单地返回一个通过 then 链接的“复合循环” promise :
// a recursive loop:
function looper(times){
var p = when.try(function(){
console.log('This should happen EVERY time looper() is called');
console.log('This shouldn’t happen if looper() is called again by next().');
});
for(var i = 0;i < times; i++){
p = p.then(function(){
console.log('This should happen EVERY time looper() is called');
});
}
return p;
};
以我的拙见,这比检查 bool 值和多余延迟对象的递归调用简单得多。它利用了 Promise 的优势,而不是退回到回调中。
现在,如果您想要一个仅在第一次执行某些操作的函数,您可以这样做:
function initOnce(){
if(!initOnce.wasCalled){ // functions are objects in JS
// initial actions
initOnce.wasCalled = true;
}
// other actions
}
这与 Promise 一样有效:
function initOnce(){
var p = when.try();
if(!initOnce.wasCalled){ // functions are objects in JS
// initial actions
p = p.then(initialHandler);
initOnce.wasCalled = true;
}
// other actions
p = p.then(otherActions);
return p;
}
关于javascript - Promise 循环每次执行一些事情,而另一些事情只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22977270/