顶层 await


🌐 Top-level await

await 关键字可以在 ECMAScript 模块的顶层主体中使用。

🌐 The await keyword may be used in the top level body of an ECMAScript module.

假设有一个 a.mjs 文件,其中包含

🌐 Assuming an a.mjs with

export const five = await Promise.resolve(5); 

还有一个 b.mjs,内容是

🌐 And a b.mjs with

import { five } from './a.mjs';

console.log(five); // Logs `5` 
node b.mjs # works 

如果顶层的 await 表达式永远不会被解析,node 进程将会以 13 状态码 退出。

🌐 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`
});