Callback on successful completion of recursion

145 Views Asked by At

I am following Folder Drag Drop for folder upload.

function onDrop(e) {
  e.preventDefault();
  e.stopPropagation();
  var items = e.dataTransfer.items;
  for (var i=0; i<items.length; i++) {
    var item = items[i].webkitGetAsEntry();
    if (item) {
      traverseFileTree(item, path="", function(){
        //Recursion Complete (Not invoked)
      });
    }
  }
}
var setFlag = true;  
function traverseFileTree(item, path, callback) {
  path = path || "";
  if (item.isFile) {
    item.file(function(file) {

       if(setFlag)callback(null);
    });
  } else if (item.isDirectory) {
    var dirReader = item.createReader();
    dirReader.readEntries(function(entries) {
      for (var i=0; i<entries.length; i++)
        if(entries[i].isDirectory)setFlag = false;

      for (var i=0; i<entries.length; i++) {
        traverseFileTree(entries[i], path + item.name + "/",callback);
      }
    });
  }
}

The above condition check for end of recursion does not work. Since the number of nested files and folders vary, any efficient method to check for end of recursion.

1

There are 1 best solutions below

1
On

How are you supposed to do that when your traverseFileTree doesn't have a third parameter, which would be the callback?

function traverseFileTree(item, path, CALLBACK){...}

Also, that function, while not being assigned to parameter, doesn't even get called inside that function. How do you expect it to run?

You need to add some logic to indicate to your function that it has accessed all nodes. Then you call the callback.:

function traverseFileTree(item, path, callback){
  ...
  if(allNodesAccessed) callback.call(null);
  ...
}