Javascript 如何确定文件遍历何时结束?
我想创建自己的拖放组件,我使用以下方法: 一切正常,但我想知道文件遍历何时结束,因为我想创建一个字符串数组,其中包含文件名,然后执行某项操作。 traverseFileTree函数包含回调,因此存在异步任务。我需要等到回调完成,我不知道怎么做。我会使用jQuery.Deffered,但traverseFileTree是从循环调用的,此外,这是一个递归函数Javascript 如何确定文件遍历何时结束?,javascript,drag-and-drop,typescript,Javascript,Drag And Drop,Typescript,我想创建自己的拖放组件,我使用以下方法: 一切正常,但我想知道文件遍历何时结束,因为我想创建一个字符串数组,其中包含文件名,然后执行某项操作。 traverseFileTree函数包含回调,因此存在异步任务。我需要等到回调完成,我不知道怎么做。我会使用jQuery.Deffered,但traverseFileTree是从循环调用的,此外,这是一个递归函数 this.dndElement.addEventListener('drop', (ev: any) => { var items
this.dndElement.addEventListener('drop', (ev: any) => {
var items = ev.dataTransfer.items;
for (var i = 0; i < items.length; i++) {
this.traverseFileTree(items[i].webkitGetAsEntry());
}
// i want to wait until callbacks in the traverseFileTree are done and do sth with fileNames array
});
public traverseFileTree(item, path?) {
path = path || "";
if (item.isFile) {
item.file((file) => {
this.fileNames.push(file.name);
});
} else if (item.isDirectory) {
var dirReader = item.createReader();
dirReader.readEntries((entries) => {
for (var j = 0; j < entries.length; ++j) {
this.traverseFileTree(entries[j], path + item.name + "/");
}
});
}
}
我得到1个文件,2个文件,5个文件,6个文件,但3个文件,4个文件没有。为什么?你在这里开始:
this.traverseFileTree(items[i].webkitGetAsEntry());
然后函数
publictraversefiletree(item,path?{
接管。函数是sync(即使是递归的)。一旦它返回,当循环结束时,您应该已经处于良好状态,文件名数组的长度为0,所以事情会异步发生…我只想等待,直到遍历文件的每个文件名都添加到文件名数组,然后使用此数组执行某项操作。是否有任何通用解决方案将文件或文件夹拖放到div,然后创建f数组你叫什么名字?
Adir
Bdir
1File
2File
Cdir
3File
4File
5File
6File
this.traverseFileTree(items[i].webkitGetAsEntry());