I have a sticky problem I am trying to solve. To illustrate the problem, I will use a familiar scenario: traversing a directory. I know there are tons of libraries out that that already traverse a directory. However, that's not what I'm trying to do. Traversing a directory is just a metaphor for my problem.
Basically, I have the following:
structure: [],
traverseDirectory: function(path) {
var scope = this;
var promise = new Promise(function(resolve, reject) {
openDirectory(path, function(results) {
for (var i=0; i<results.length; i++) {
if (results[i].type === 'directory') {
scope.traverseDirectory(results[i].name);
} else {
scope.structure.push({ filename:name });
}
}
resolve(scope.structure);
});
});
return promise;
},
getDirectoryStructure: function(path) {
this.traverseDirectory(path)
.then(function(results) {
// Print out all of the files found in the directories.
console.log(JSON.stringify(results));
}
;
}
My problem is the .then
of getDirectoryStructure
fires before the directory is actually traversed. Its not waiting like I thought it would. Plus, I'm not sure how to "pass" (not sure if that's the right word) the promise around as I'm recursing through the directory structure. Can I even do what I'm trying with promises?
Thank you for any help.