javascript - 递归 promise 链末尾的链式操作

标签 javascript recursion promise bluebird

我目前正在尝试使用 Bluebird 库将另一个 .then() 链接到递归 promise 链的末尾。

我的代码看起来像这样

exports.fetchAll = function() {

  fetchItems = function(items) {
    return somethingAsync()
      .then(function(response) {
        items.push(response.data);
        if (response.paging.next) {
          fetchItems();
        } else {
          return items;
        }
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  return fetchItems([], 0);
}

/// In Some other place

fetchAll().then(function(result){ console.log(result); });

到目前为止, fetchAll 调用结束时的 .then 会立即返回。如何使其在递归链的末尾执行?

最佳答案

当您递归调用函数fetchItems时,您需要返回值,如下所示

if (response.paging.next) {
  return fetchItems();        // Note the `return` statement
} else {
  return items;
}

现在,fetchItems 返回另一个 Promise,并且只有在该 Promise 得到解决后才会调用最后的 then

关于javascript - 递归 promise 链末尾的链式操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091405/

相关文章:

javascript - 图像作为模态的 href

python - 检测到一个方法是递归的而不调用它?

Android从递归算法更新ui

typescript 类型最大递归限制为 9

promise - RxJs 缓冲直到数据库插入( promise )

swift - PromiseKit 如何返回 "when(resolved)"作为 promise ?

javascript - 我应该如何转义这个 JavaScript 正则表达式(RFC 2822 电子邮件验证器)

javascript - 为什么 ProgressEvent.lengthComputable 为假?

javascript - 使用 promise 实现超时 - 抛出错误

javascript - React 中的 JSON 对象解析问题