我试图使用javascript promises递归调用异步函数,但是没有找到可行的模式。
这是我想象的可行方法:
var doAsyncThing = function(lastId){
new Promise(function(resolve, reject){
// async request with lastId
return resolve(response)
}
}
var recursivelyDoAsyncThing = function(lastId){
doAsyncThing(lastId).then(function(response){
return new Promise(function(resolve, reject){
//do something with response
if(response.hasMore){
//get newlastId
return resolve(recursivelyDoAsyncThing(newLastId));
}else{
resolve();
}
});
});
}
recursivelyDoAsyncThing().then( function(){
console.log('done');
});
为什么这不起作用?我误解了什么?
有没有更好的模式来解决这个问题?
答案 0 :(得分:2)
recursivelyDoAsyncThing
需要返回Promise以继续链。在您的情况下,您需要做的就是让doAsyncThing
返回其承诺:
var doAsyncThing = function(lastId){
// Notice the return here:
return new Promise(function(resolve, reject){
然后将return
添加到您的doAsyncThing
电话中,如下所示:
var recursivelyDoAsyncThing = function(lastId){
// Notice the return here:
return doAsyncThing(lastId).then(function(response){
答案 1 :(得分:2)
您在recursivelyDoAsyncThing
功能中遗漏了function recursivelyDoAsyncThing(lastId) {
return doAsyncThing(lastId).then(function(response) {
//^^^^^^
//do something with response
if (response.hasMore) {
//get newlastId
return recursivelyDoAsyncThing(newLastId);
} else {
return; // undefined? Always return a useful value
}
});
}
。你应该one of the recommended ways:
{{1}}
答案 2 :(得分:1)
我有一个简单的递归承诺示例。该示例基于数字的factorial
计算。
let code = (function(){
let getFactorial = n =>{
return new Promise((resolve,reject)=>{
if(n<=1){
resolve(1);
}
resolve(
getFactorial(n-1).then(fact => {
return fact * n;
})
)
});
}
return {
factorial: function(number){
getFactorial(number).then(
response => console.log(response)
)
}
}
})();
code.factorial(5);
code.factorial(6);
code.factorial(7);