title: delaying function execution only after completing async recursive function.
body: <p>I created a file upload form with drag on drop, which iterates recursively over the dropped folder and uploads the file and folders, and adds them to a JSTree instance.</p>
  
  <p>here's the drop callback</p>
  
  <pre><code>function drop(evt){
      evt.stopPropagation();
      evt.preventDefault();
  
  
      //get selected node (created by jsTree)
      var parent_id = $('#treeContainer').jstree('get_selected').attr('data-attr-itemid');
      var theNodeId = $('#treeContainer').jstree('get_selected').attr('id');
  
      for (var i=0; i&lt;items.length; i++) {
          var item = items[i].webkitGetAsEntry();
          if (item) {
              traverseFileTree2(item,parent_id,theNodeId);
          }
      }
     //THIS RUNS BEFORE RECUSIVE FUNCTION IS COMPLETED
     addFilesToUploadQueue(filesToQueue);
  }
  </code></pre>
  
  <p>and here's the recursive traversing function </p>
  
  <pre><code>var filesToQueue = [];
  function traverseFileTree2(item, parent_id, theNodeId, path) {
      if (item.isFile) {
          item.file(function(file){
            //add parent id, and adds to array to be queued for upload
            file.parent_id = parent_id;
            filesToQueue.push(file);
          })
         return;
      }
      else if (item.isDirectory) {
  
         var dirName = item.name;
         var url = '&lt;?php echo $this-&gt;Html-&gt;url(array('controller'=&gt;'nodes', 'action'=&gt;'addchild'));?&gt;';
         var data = {'parent_id':parent_id, 'name':dirName, 'type':'Directory'};
  
         $.post(url,data,function(result){
  
              //adds directory node to tree
              $("#treeContainer").jstree('open_node','#'+theNodeId);
              $("#treeContainer").jstree('create', '#'+theNodeId, 'last', result,null,true);
  
              parent_id = result["attr"]["data-attr-itemid"];
              theNodeId = result["attr"]["id"];
              var dirReader = item.createReader();
  
              dirReader.readEntries(function(entries) {
                  for (var i=0; i&lt;entries.length; i++) {
                      traverseFileTree2(entries[i], parent_id, theNodeId, path + item.name + "/");
                  }
              });
      }, 'json');
  }
  </code></pre>
  
  <p>}</p>
  
  <p>My problem here is that the function <code>addFilesToUploadQueue(filesToQueue)</code> runs before the recursive async function <code>traverseFileTree2</code> is completed. I'd prefer not use callbacks, if this can be done using promises.</p>