2016-02-19 85 views
2

我正在使用Visual Studio Online API并试图通过存储库获取分支统计信息。要做到这一点,我嵌套了我的异步调用。我正在使用request-promise来解决我的GET请求。使用request-promise嵌套的异步请求

我有是理解如何返回模式后,所有的树枝都被添加到顶级型号的问题:

当我CONSOLE.LOG结果我得到[]明显,因为它不是” t解决分支请求。

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); 
    }); 

我尝试添加.then()在foreach之后,但显然forEach不返回的承诺。

任何想法?我已经编程了14个小时,所以对我来说没有任何意义。

+1

一个对每个没有,但如果你使用。降低,而不是用一个承诺链中,减少将返回一个。 :) –

+1

使用'map'而不是'forEach',这样你就可以得到一组promise;然后将其送入'Promise.all'。或者只是使用'Promise.map',因为你正在使用蓝鸟。 – Bergi

回答

1

下面应该解决您的问题,而不是做forEach循环,我用您的承诺链中的.map()取而代之。我也在你的内心承诺中做到了这一点。此外,我已完成内部承诺,以便外部映射知道每次迭代完成的时间。

我离开了.finally(),因为这表明我们总是想要回应用户,无论填充model的结果如何。

我也建议将.catch()添加到您的外部和内部承诺,以确保您正确处理任何错误。如果发生错误,那么什么都不会处理,并且model将被返回,并且您永远不会知道在其中一次迭代中发生了与.map()有关的内部或外部承诺错误。

另外值得注意的是,request-promise实现了A +使用bluebird的承诺。

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); 
    }); 
+0

上面的代码存在一些问题: - 最后一个终于有错字,在函数中缺少'n'。 - 也RP(选项)不会从蝙蝠返回数据。我不得不在'.map(function(){})之前添加一个'.then(function(repository){return repository.value;})'除此之外它完美地工作。干杯皮特 –