如何递归调用promise函数

ben*_*phw 5 javascript recursion promise

我正在尝试使用 javascript Promise 递归调用异步函数,但尚未找到有效的模式。

这就是我想象的工作:

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');
});
Run Code Online (Sandbox Code Playgroud)

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

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

Mat*_*att 3

recursivelyDoAsyncThing需要返回一个 Promise 才能继续这条链。就您而言,您所需要做的就是doAsyncThing返回其 Promise:

var doAsyncThing = function(lastId){
  // Notice the return here:
  return new Promise(function(resolve, reject){
Run Code Online (Sandbox Code Playgroud)

然后像这样添加return到您的通话中:doAsyncThing

var recursivelyDoAsyncThing = function(lastId){
  // Notice the return here:
  return doAsyncThing(lastId).then(function(response){
Run Code Online (Sandbox Code Playgroud)