title: Node JS Promise.all and forEach
body: <p>I have an array like structure that exposes async methods. The async method calls return array structures that in turn expose more async methods. I am creating another JSON object to store values obtained from this structure and so I need to be careful about keeping track of references in callbacks.</p>
  
  <p>I have coded a brute force solution, but I would like to learn a more idiomatic or clean solution.</p>
  
  <ol>
  <li>The pattern should be repeatable for n levels of nesting. </li>
  <li>I need to use promise.all or some similar technique to determine when to resolve the enclosing routine.</li>
  <li>Not every element will necessarily involve making an async call. So in a nested promise.all I can't simply make assignments to my JSON array elements based on index. Nevertheless, I do need to use something like promise.all in the nested forEach to ensure that all property assignments have been made prior to resolving the enclosing routine.</li>
  <li>I am using the bluebird promise lib but this is not a requirement</li>
  </ol>
  
  <p>Here is some partial code - </p>
  
  <pre><code>var jsonItems = [];
  
  items.forEach(function(item){
  
    var jsonItem = {};
    jsonItem.name = item.name;
    item.getThings().then(function(things){
    // or Promise.all(allItemGetThingCalls, function(things){
  
      things.forEach(function(thing, index){
  
        jsonItems[index].thingName = thing.name;
        if(thing.type === 'file'){
  
          thing.getFile().then(function(file){ //or promise.all?
  
            jsonItems[index].filesize = file.getSize();
  </code></pre>