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