【发布时间】:2016-06-01 14:04:33
【问题描述】:
我正在使用 Visual Studio Online API 并尝试按存储库获取分支统计信息。为此,我嵌套了异步调用。我正在使用 request-promise 来解决我的 GET 请求。
我遇到的问题是了解如何在所有分支都添加到顶级模型后返回模型:
当我控制台记录结果时,我得到[] 显然因为它没有解决分支请求。
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 不会返回承诺。
有什么想法吗?我已经编程了 14 个小时,所以对我来说没有任何意义哈哈。
【问题讨论】:
-
a for each 没有,但如果你使用 .reduce 代替 Promise 链,reduce 将返回一个。 :)
-
使用
map而不是forEach,这样你就可以得到一组promise;然后将其输入Promise.all。或者只是使用Promise.map,因为您正在使用 bluebird。
标签: node.js express promise bluebird