【问题标题】:How to call promise function recursively如何递归调用promise函数
【发布时间】:2016-05-26 19:16:45
【问题描述】:

我正在尝试使用 javascript 承诺递归调用异步函数,但没有找到可行的模式。

这是我想象中的工作:

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');
});

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

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

【问题讨论】:

    标签: javascript recursion promise


    【解决方案1】:

    recursivelyDoAsyncThing 需要返回一个 Promise 才能继续链。在您的情况下,您需要做的就是让 doAsyncThing 返回它的 Promise:

    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){
    

    【讨论】:

      【解决方案2】:

      您在recursivelyDoAsyncThing 函数中缺少return。你也应该avoid the Promise constructor antipattern:

      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
          }
        });
      }
      

      【讨论】:

        【解决方案3】:

        我有一个递归承诺的简单例子。该示例是基于计算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);

        【讨论】:

        • 完美的例子,因为大多数开发人员开始使用阶乘递归。
        • 很好的例子。谢谢
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2020-01-08
        相关资源
        最近更新 更多