我有这段代码
async function addFiles(dir,tree) {
return (await readDir(dir))
.map(async (name) => {await readDir(dir); return name;})
}
但不幸的是,它只返回一堆 promises,因为 map 中的异步函数没有被等待。我想知道是否有任何方法可以在上面的代码中等待映射函数。
我有这段代码
async function addFiles(dir,tree) {
return (await readDir(dir))
.map(async (name) => {await readDir(dir); return name;})
}
但不幸的是,它只返回一堆 promises,因为 map 中的异步函数没有被等待。我想知道是否有任何方法可以在上面的代码中等待映射函数。
尝试
async function addFiles(dir,tree) {
const files = await readDir(dir)
await Promise.all(files.map(async (name) => {await readDir(dir); return name;})
}
async function addFiles(dir, tree) {
const files = await readDir(dir);
return Promise.map(files, async (name) => { await readDir(dir); return name; });
}
return Promise.all((await readDir(dir)).map(...));
应该可以工作。不确定是否必须是await Promise.all(...)
。 - Felix Kling