Nested async requests using request-promise
<p>I'm working with the Visual Studio Online API and trying to get branch stats by repository. To do this I've nested my async calls. I'm using <a href="https://www.npmjs.com/package/request-promise" rel="nofollow">request-promise</a> to resolve my GET requests. </p>

<p>The issue I'm having is understanding how to return the model after all the branches have been added to the top-level model:</p>

<p>When I console.log the result I get <code>[]</code> obviously since it isn't resolving the branch requests.</p>

<pre><code>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);
  });
</code></pre>

<p>I tried to add a <code>.then()</code> after the foreach but obviously a <code>forEach</code> doesn't return a promise. </p>

<p>Any ideas? I've been programming for 14 hours so nothing is making sense to me haha.</p>