Angular JS中的递归承诺

时间:2014-01-14 16:01:15

标签: javascript html5 angularjs promise q

我希望遍历html5文件系统,并在遍历所有文件后进行某种通知。

我正在使用filer,它是html文件系统库的包装器

为了使用这个启动递归文件系统walker:

filerService.ls(filerService.fs.root, function(entries){
  for(var i = 0; i < entries.length; i ++) {
    traverseFileTree(entries[i]);
  }
});

递归函数:

function traverseFileTree(item) {

    if(item.isFile) {
         console.log("item is file: " + item.name); 
         //do something with file here

    } else if (item.isDirectory) {
        console.log("item is directory: " + item.name); 

        filerService.ls(item, function(entries) {

            for(var i = 0; i < entries.length; i ++) {
                traverseFileTree(entries[i]);
            }
        }); 
    }
};

现在我想做以下事情:

var promise = walkFileTree() //this method should start the recursive methods and return a promise

promise.then(function(){
  //notify user that the filewalker has completed
})

任何人都有关于如何实现这一目标的一些指示?

1 个答案:

答案 0 :(得分:3)

可以使用promises数组(每个子目录一个)和$q.all()来完成。未经测试的解决方案概要是:

function walkFileTree(item) {
    var d = $q.defer(), promises = [d.promise]; // we need at least one promise because we do not know beforehand the number of included directories
    if( typeof(item) === "undefined" ) item = filerService.fs.root;
    filerService.ls(item, function(entries){
        for(var i = 0; i < entries.length; i ++) {
            promises.push(traverseFileTree(entries[i]));
        }
        d.resolve();
    });
    return $q.all(promises);
}

function traverseFileTree(item) {
    var d = $q.defer();
    if(item.isFile) {
        console.log("item is file: " + item.name);
        //do something with file here
        d.resolve();
        return d.promise;
    }
    else if (item.isDirectory) {
        console.log("item is directory: " + item.name); 

        return walkFileTree(item);
    }
};

请注意,walkFileTree(item)将迭代该项,而walkFileTree()将迭代根。

正如我所说,这是未经测试的,可能需要调整,但它证明了(我认为)解决方案的大纲。