【发布时间】:2020-09-08 00:21:23
【问题描述】:
我有一个看起来像这样的函数:
function populateMap(directory: string, map, StringMap) {
fs.promises.readdir(directory).then(files: string[]) => {
files.forEach(file: string) => {
const fullPath = path.join(directory, file);
fs.stat(fullPath, (err: any, stats: any) => {
if (stats.isDirectory()) {
populateFileMap(fullPath, fileMap);
} else {
fileMap[file] = fullPath;
}
});
});
});
}
我想要做的是递归遍历父目录并将文件名映射存储到它们的路径。我知道这是有效的,因为如果我在 fileMap[file] = fullPath 下放置一个 console.log(fileMap),在目录中最深的文件之后,列表就会正确填充。
在调用此函数的文件中,我希望能够拥有完整的地图
function populateMapWrapper(dir: string) {
const fileMap: StringMap = {};
populateMap(dir, fileMap);
//fileMap should be correctly populated here
}
我尝试过使 populateMap 异步,将 .then() 添加到包装函数中调用它的位置,但如果我在 then() 函数中使用 console.log(fileMap),则 fileMap 为空。
我不确定这是因为 javascript 如何传递变量,还是我对 Promise 的理解存在差距,但我想知道是否有其他方法可以做到这一点。
【问题讨论】:
-
是的,将回调样式转换为 Promise 是一个好主意,就像将其设置为
async function一样,您可以在其中await这些 Promise。还有don't useforEach.
标签: javascript typescript promise es6-promise fs