Top-Level Await Stages Module Setup
Top-level await lets module setup pause on async steps: statements after the await run only once the wait resolves, with no IIFE wrapper needed.
Code
// 顶层 await:模块初始化可以按顺序等待,无需 IIFE 包裹
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log('stage 1: loading config');
const t0 = Date.now();
await wait(30);
console.log('config ready after', Date.now() - t0, 'ms');
// 之后的语句只在等待完成后执行:初始化天然按序
const config = { mode: 'ready', retries: 2 };
console.log('config:', config.mode, config.retries);
// 第二段 setup 同样按序执行
await wait(20);
console.log('stage 2: warmup done, exports usable');Output
Captured from a sandboxed run of this snippet in the build pipeline.
stage 1: loading config
config ready after 31 ms
config: ready 2
stage 2: warmup done, exports usableHow the snippet works
The working surface is the function wait — everything else is wiring.
Every asynchronous step is awaited, so rejections surface where the call happens.
Applying it
The primary signature is const wait = (ms)
Running the file prints labeled results such as stage 1: loading config, config ready after, config: — each operation’s effect is visible in the output.
Statements that matter
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await wait(30);
await wait(20);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `wait` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.