随着ES2022 接受了顶级等待,我想知道假设它await import("./path/to/module")
根本没有超时是否可以保存。这是我想做的:
// src/commands/do-a.mjs
console.log("Doing a...");
await doSomethingThatTakesHours();
console.log("Done.");
// src/commands/do-b.mjs
console.log("Doing b...");
await doSomethingElseThatTakesDays();
console.log("Done.");
// src/commands/do-everything.mjs
await import("./do-a");
await import("./do-b");
这是我在运行时期望看到的node src/commands/do-everything.mjs
:
Doing a...
Done.
Doing b...
Done.
我找不到任何关于顶级等待超时的提及,但我想知道我想要做的是否是对该功能的滥用。理论上,Node.js(或 Deno)可能会在达到某个预定义的时间上限(例如 30 秒)后抛出异常。
以下是我在 TLA 之前处理相同任务的方式:
// src/commands/do-a.cjs
import { autoStartCommandIfNeeded } from "@kachkaev/commands";
const doA = async () => {
console.log("Doing a...");
await doSomethingThatTakesHours();
console.log("Done.");
}
export default doA;
autoStartCommandIfNeeded(doA, __filename);
// src/commands/do-b.cjs
import { autoStartCommandIfNeeded } from "@kachkaev/commands";
const doB = async () => {
console.log("Doing b...");
await doSomethingThatTakesDays();
console.log("Done.");
}
export default doB;
autoStartCommandIfNeeded(doB, __filename);
// src/commands/do-everything.cjs
import { autoStartCommandIfNeeded } from "@kachkaev/commands";
import doA from "./do-a";
import doB from "./do-b";
const doEverything = () => {
await doA();
await doB();
}
export default doEverything;
autoStartCommandIfNeeded(doEverything, __filename);
autoStartCommandIfNeeded()
__filename
如果匹配则执行函数require.main?.filename
。