递归承诺链末端的链式动作

Chain action at the end of a recursive promise chain

本文关键字:承诺 递归      更新时间:2023-09-26

我目前正在尝试将另一个。then()链到Bluebird库的递归承诺链的末端。

我的代码看起来像这样

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返回另一个承诺,并且只有在该承诺被解决后才会调用最后的then