我在服务器上有一个文件夹层次结构。我想以异步和递归方式循环遍历此层次结构,并在找到文件时调用自定义方法。
现在,我的代码如下所示:
searchFile(root, handleFile);
// loop over all folders recursively, then handle files
function searchFile(item, callbackWhenFile) {
if (itIsFolder(item)) {
$http.get("api.call.com/children/" + item.id)
.then(function (children) {
angular.forEach(children,
function (child) {
searchFile(child, callbackWhenFile);
});
});
}
else {
// this is not a folder, so this is a file
callbackWhenFile(item);
}
}
使用回调代替 Promise 并不是一件好事。
但我试图找到一种方法让它与 Promise 一起工作,但没有机会。
在理想的解决方案中,我想做这样的事情:
searchFile(root).then(function (file) {
handleFile(file)
});
我查看了 $q.all、$q.when,但似乎没有任何内容适合这种情况。事实上,我们不知道我们将拥有的文件数量,这使得问题变得困难。
有人知道如何解决这个问题吗?
编辑答案
Promises are not the way to go.
使用 RxJS 和可观察对象,可以写成:
getFileStream(root).subscribe(function (file) {
handleFile(file);
});
function getFileStream(root) {
var source = Rx.Observable.create(function (observer) {
observeFiles(observer, root);
});
return source;
}
function observeFiles(observer, item) {
if (itIsFolder(item)) {
$http.get("api.call.com/children/" + item.id)
.then(function (children) {
angular.forEach(children,
function (child) {
searchFile(observer, child);
});
});
}
else {
observer.onNext(item);
}
}
最佳答案
Promise 只能解析为单个值。该值可以是对象或数组,但最终它是单个值 - 而不是流。
您的“理想解决方案”被定义为好像它确实生成了流,但这是不可能的。
你可以:
关于javascript - Promise & Recursion,如何在没有回调的情况下处理找到的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480559/