我正在使用 Visual Studio Online API 并尝试按存储库获取分支统计信息。为此,我嵌套了异步调用。我正在使用request-promise解决我的 GET 请求。
我遇到的问题是了解如何在将所有分支添加到顶级模型后返回模型:
当我console.log结果时,我显然得到了[]
,因为它没有解决分支请求。
var model = [];
rp(options)
.then(function(repos) {
repos.value.forEach(function(repository) {
var repo = {
id: repository.id,
name: repository.name,
branches: []
};
var branchOptions = options;
branchOptions.url = config.endPoints.base + config.endPoints.branches(repository.id);
rp(branchOptions)
.then(function(branches) {
branches.value.forEach(function(branch) {
repo.branches.push({
name: branch.name,
behind: branch.behindCount,
ahead: branch.aheadCount
});
})
}).then(function() {
model.push(repo);
});
});
}).finally(function(){
console.log(model);
res.json(model);
});
我尝试在 foreach 之后添加 .then()
但显然 forEach
不会返回 promise 。
有什么想法吗?我已经编程了 14 个小时,所以对我来说没有任何意义,哈哈。
最佳答案
下面的内容应该可以解决您的问题,而不是执行 forEach
循环,我已将其替换为 promise 链中的 .map()
。我也是在你内心的 promise 之内做到了这一点。此外,我已使内部 promise 在完成时返回,以便外部映射知道每次迭代何时完成。
我留下了.finally()
,因为这表明我们始终希望响应用户,无论填充模型
的结果如何。
我还建议将 .catch()
添加到您的外部和内部 promise 中,以确保您正确处理任何错误。按照目前的情况,如果发生错误,则不会处理该错误,并且将返回 model
,并且您永远不会知道使用 .map()
的迭代之一发生了错误关于内在或外在的 promise 。
还值得注意的是 request-promise
使用 bluebird
实现 A+ Promises 。
var model = [];
rp(options)
.map(function(repository) {
var repo = {
id: repository.id,
name: repository.name,
branches: []
};
var branchOptions = options;
branchOptions.url = config.endPoints.base + config.endPoints.branches(repository.id);
return rp(branchOptions)
.map(function(branch){
repo.branches.push({
name: branch.name,
behind: branch.behindCount,
ahead: branch.aheadCount
});
})
.then(function() {
model.push(repo);
});
})
.finally(fuction() {
console.log(model);
return res.json(model);
});
关于javascript - 使用 request-promise 嵌套异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35514797/