Recursive Promises?

Ivan Bacher picture Ivan Bacher · Jan 15, 2014 · Viewed 11.4k times · Source

I would like to iterate over all files located in the HTML 5 file system and have some event get started once the iteration is complete. Since this is async + promises im having a hard time trying to grasp how it should work.

I am using a angularJS and have created a service to encapsulate html 5 file system specific features.

This is the recursive function:

function walkDirectory(path) {

    fileSystem.getFolderContents(path) //this is the services and it returns a promise containing all files in the current folder or directory
        .then(function(entries) {

            for (var i = 0; i < entries.length; i++) {

                if(entries[i].isFile) {
                    console.log("is File: " + entries[i].name);
                    //do something with file here
                } 
                else if (entries[i].isDirectory) {
                    console.log("is Dir: " + entries[i].name);
                    walkDirectory(entries[i].fullPath);
                }
            }
        });
};

ideally i would like to call the function like so, and have it return a promise which gets executed once all files have been traversed.

walkDirectory("/").then( function() {
  console.log(done);
});

Any tips/ ideas how this can be achieved?

an idea would be to have an array of promises and add a new promise to the array for every file/directory. My attempt:

function walkDirectory(path) {

    var defer= $q.defer();
    var promises = [defer.promise];

    fileSystem.getFolderContents(path)
        .then(function(entries) {

            for (var i = 0; i < entries.length; i++) {

                if(entries[i].isFile) {
                    console.log("is File: " + entries[i].name);
                    //do something with file here
                    defer.resolve();
                    promises.push(defer.promise);
                } 
                else if (entries[i].isDirectory) {
                    console.log("is Dir: " + entries[i].name);
                    promises.push(walkDirectory(entries[i].fullPath));
                }
            }
        });

    return $q.all(promises);
};

walkDirectory("/").then(function() {
    console.log("done");
});

This doesn't seem to be working since done is never displayed in the console.

Answer

SLaks picture SLaks · Jan 15, 2014

You're returning the array before you populate it.

Instead, you need to return $q.all(promises) within the then() callback, and return the outer promise:

return fileSystem.getFolderContents(path).then(function(entries) {
    return $q.all(entries.map(function(e) {
        if (e.isFile) {
            // Do something
            return null;  // Don't wait for anything
        } else {
            // Do something
            return walkDirectory(e.fullPath);
        }
    }));
});