title: jQuery Deferred objects for a requests in directory tree form
body: <p>I want to do AJAX requests to follow a tree like structure, kinda like a file system directory where directories link to other directories. Only in my case I follow a REST API that where I follow IDs. Like with every request I receive a list of IDs of the subdirectories (and "files" in the end).</p>
  
  <p>So what I want to do is to make AJAX calls inside AJAX calls using forEach. I want to check whether an error occurred and I want to make sure that it waits for the requests to complete so that in the end I am able to process and return the data I received. How would I do that?</p>
  
  <p>So I basically have JSON like this and start from /directories. I want to get all the files and return them from a function as one big JSON.</p>
  
  <p>/directories</p>
  
  <pre><code>["directoryA", "directoryB"]
  </code></pre>
  
  <p>/direcotry/directoryA</p>
  
  <pre><code>["subDirectory1", "subDirectory2"]
  </code></pre>
  
  <p>/direcotry/directoryB</p>
  
  <pre><code>["subDirectory4"]
  </code></pre>
  
  <p>/directory/subDirectory1</p>
  
  <pre><code>["fileA", "fileB"]
  </code></pre>
  
  <p>/directory/subDirectory2</p>
  
  <pre><code>["fileC"]
  </code></pre>
  
  <p>/file/fileA</p>
  
  <pre><code>{"some content"}
  </code></pre>
  
  <p>/file/fileB</p>
  
  <pre><code>{"Hello world"}
  </code></pre>
  
  <p>/file/fileC</p>
  
  <pre><code>{"nickname": "Clown", "id": 9247234}
  </code></pre>
  
  <p>...</p>
  
  <p>My code currently about this (sorry, the original one is CoffeeScript and does lots of other stuff helping to decide what to get and how to sort them in the end):</p>
  
  <pre><code>function getFiles(settings){
    $.ajax("/directories", settings, function(directories) {
      data.forEach(function (directory) {
        $ajax("/directory/" + directory, settings, function(subdirectory) {
          // and so on, in the innermost processing the file contents,
          // but unable to return them.
        });
      });
    });
  }
  </code></pre>