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.

JavascriptConfig Management

Code

javascriptsnippet
15 lines
// 顶层 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 usable

How 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

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.