我已经成功创建了一个根据目录创建文件夹的函数。
然而,当我试图使用Promise.all()
将for of
转换为map()
方法时,错误没有得到相同的处理。
import { readdir, mkdir } from 'fs/promises';
const copyUsingFor = async (target) => {
try {
const dir = await readdir(`./test`, { withFileTypes: true });
for (const item of dir) {
if (item.isDirectory()) {
try {
await mkdir(`./${target}`);
}
catch (err) {
throw err;
}
}
}
}
catch (err) {
console.log(`desired err handling`);
throw err;
}
}
const copyUsingMap = async (target) => {
try {
const dir = await readdir(`./test`, { withFileTypes: true });
Promise.all(
dir.map(async item => {
if (item.isDirectory()) {
try {
await mkdir(`./${target}`);
}
catch (err) {
throw err;
}
}
})
)
}
catch (err) {
throw err;
}
}
copyUsingFor(`../`).catch(err => console.log(`An error occurred: ${err}`)) // <- Works.
copyUsingMap(`../`).catch(err => console.log(`An error occurred: ${err}`)) // <- Gives "triggerUncaughtException".
我猜这是因为我有一个async内部另一个,但不能弄清楚为什么它不工作相同。
谢谢!
您在Promise.all
前面错过了await
,仅此而已。因此,Promise.all
内部发生的事情与程序流的其余部分是分离的。
旁注:catch (err) { throw err }
是一个no-op。你可以摆脱整个try
/catch
,如果你不做任何事情,除了重新抛出错误。这感觉有点像在函数x => x
的调用中包装东西。