如何递归调用promise函数

时间:2016-02-15 18:46:07

标签: javascript recursion promise

我试图使用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');
});

为什么这不起作用?我误解了什么?

有没有更好的模式来解决这个问题?

3 个答案:

答案 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);