title: Recursively Parsing JSON Asynchronously
body: <p>Let's say I have these JSON files:</p>
  
  <p><strong><em>company.json</em></strong></p>
  
  <pre><code>{
    "name" : "Big Corp",
    "employees" : [
      "employees/johnd.json"
    ]
  }
  </code></pre>
  
  <p><strong><em>employees/johnd.json</em></strong></p>
  
  <pre><code>{
    "name" : "John Doe",
    "gender" : "male",
    "contact" : "../contacts/johnd.json"
  }
  </code></pre>
  
  <p><strong><em>contacts/johnd.json</em></strong></p>
  
  <pre><code>{
    "email" : "jd@example.com",
  }
  </code></pre>
  
  <p>They all relate to each other, and each value ending with <code>.json</code> is a pointer to another file, relative to the file that it is currently in.</p>
  
  <p>In Node, synchronously connecting these files into a tree is not a hard task, but I'm having some trouble finding a good asynchronous pattern for it. Every time I think I've cracked it in a bug-free and efficient manner, something trips me up again. Perhaps I'm just tired. o_O</p>
  
  <p>I've written a completely synchronous version of what I want, and it works perfectly:</p>
  
  <pre><code>var path = require('path');
  var fs = require('fs');
  
  function json(jsonPath) {
  
    var obj = JSON.parse( fs.readFileSync(jsonPath, 'utf8') );
  
    recurse(obj, jsonPath);
  
    return obj;
  
  }
  
  function recurse(obj, fromPath) {
  
    for (var i in obj) {
  
      if (isJsonPath(obj[i]))
        obj[i] = json( path.join( path.dirname(fromPath), obj[i]) );
  
      if (obj[i] != null &amp;&amp; typeof obj[i] == 'object')
        recurse(obj[i], fromPath)
  
    }
  }
  
  function isJsonPath (str) {
  
    return typeof str == 'string' &amp;&amp; /.json$/.test(str);
  
  }
  
  console.log( json('company.json') );
  </code></pre>
  
  <p>The above code, in combination with the files and structure mentioned previously, returns the correct object:</p>
  
  <pre><code>{
    "name":"Big Corp",
    "employees":[
      {
        "name":"John Doe",
        "gender":"male",
        "contact":{
          "email":"jd@example.com"
        }
      }
    ]
  }
  </code></pre>
  
  <p>How would the SO community approach turning this into an asynchronous piece of code? For example, having asynchronous calls to the file system using <code>readFile</code> instead of <code>readFileSync</code>, such that the following would output the same result:</p>
  
  <pre><code>json('company.json', function (err, data) {
  
    console.log(data);
  
  });
  </code></pre>