顶层的 await
await
关键字可以用在 ECMAScript 模块的顶层主体中。
假设 a.mjs
具有
export const five = await Promise.resolve(5);
并且 b.mjs
具有
import { five } from './a.mjs';
console.log(five); // 记录 `5`
node b.mjs # 有效
如果顶层 await
表达式永远无法解析,则 node
进程将以 13
状态码退出。
import { spawn } from 'node:child_process';
import { execPath } from 'node:process';
spawn(execPath, [
'--input-type=module',
'--eval',
// 永不解决的 Promise:
'await new Promise(() => {})',
]).once('exit', (code) => {
console.log(code); // 记录 `13`
});
The await
keyword may be used in the top level body of an ECMAScript module.
Assuming an a.mjs
with
export const five = await Promise.resolve(5);
And a b.mjs
with
import { five } from './a.mjs';
console.log(five); // Logs `5`
node b.mjs # works
If a top level await
expression never resolves, the node
process will exit
with a 13
status code.
import { spawn } from 'node:child_process';
import { execPath } from 'node:process';
spawn(execPath, [
'--input-type=module',
'--eval',
// Never-resolving Promise:
'await new Promise(() => {})',
]).once('exit', (code) => {
console.log(code); // Logs `13`
});