我目前正在尝试使用 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/