[英]Chain action at the end of a recursive promise chain
I'm currently attempting to chain another .then() to the end of a recursive promise chain with the Bluebird
library. 我目前正在尝试将另一个.then()链接到
Bluebird
库的递归承诺链的末尾。
My code looks something like this 我的代码看起来像这样
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); });
As of now, .then
at the end of the fetchAll call is returned immediately. 到目前为止,
.then
在fetchAll调用结束时立即返回。 How do I make it such that it executes at the end of my recursive chain? 如何使它在递归链的末尾执行?
When you are recursively invoking the function, fetchItems
, you need to return the value, like this 当递归调用
fetchItems
函数时,您需要返回该值,就像这样
if (response.paging.next) {
return fetchItems(); // Note the `return` statement
} else {
return items;
}
Now, the fetchItems
returns another promise and the then
at the end will be invoked only after that promise is resolved. 现在,
fetchItems
返回另一个promise,只有在解决了promise后, then
才会被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.