使用request-promise嵌套asynchronous请求
我正在使用Visual Studio Online API并试图通过存储库获取分支统计信息。 要做到这一点,我嵌套我的asynchronous调用。 我正在使用请求承诺来解决我的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
循环,我用你的承诺链中的.map()
代替了。 我也是在你内在的承诺下做到这一点的。 此外,我已经完成了内部承诺,所以外部映射知道每次迭代完成的时间。
我离开了.finally()
因为这表明我们总是要回应用户,而不pipe填充model
的结果如何。
我也build议将.catch()
添加到外部和内部的承诺,以确保您正确处理任何错误。 如果发生错误,那么什么都不会处理, model
将被返回,并且你永远不会知道你的一个迭代在内部或外部承诺的.map()
上发生了错误。
另外值得注意的是, 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); });