我需要检查一些目录树中的文件,然后在服务器上创建相同的目录结构,还要创建文件列表以上传到服务器。所以我意识到我需要用承诺包装我的dirs迭代器,这样我就可以在“.then()”上获得最终文件列表:
export function uploadHandler(filesAndDirs, currentDirectory) {
return (dispatch, getState) => {
filesToUpload = [];
iterate(filesAndDirs, currentDirectory).then((whatResolved) => {
console.log(whatResolved + ' is resolved');
// console.log(filesToUpload);
});
}
}
但是我在解决我的承诺时遇到了一些麻烦,因为使用递归我不确切知道哪个文件/目录是最后一个:
function iterate(filesAndDirs, currentDirectory) {
return new Promise(function(resolve) {
for (let i = 0; i < filesAndDirs.length; i++) {
if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') {
let dir = filesAndDirs[i];
createDirectory(dir.name, currentDirectory._id).then((directory) => {
dir.getFilesAndDirectories().then((subFilesAndDirs) => {
iterate(subFilesAndDirs, directory).then(() => {
if (i + 1 == filesAndDirs.length) resolve('+++ by dir');
});
});
});
} else {
filesToUpload.push({
file: filesAndDirs[i],
directory: currentDirectory
});
// If last item is file then I need to resolve the main promise
// but same time if I will resolve promise here then
// whole chain will break couse subdirectories handling async
}
};
});
}
我使它适用于[dir]输入,但如果[dir,file]输入我无法处理它。我能在这做什么?也许在这里使用Promise是个坏主意?