What is top-level await and where can you use it in Node.js?
It lets you use await directly at the top of a file without wrapping it in an async function. It works only in ES modules, and it delays anything that imports that module until the promise settles.
Explain it simply
Normally await is allowed only inside an async function, so scripts often start with an ugly async function main() {...} main(); wrapper. In an ES module, the whole file behaves as if it were inside an async function, so you can write await on line one.
Example
// config.mjs
import { readFile } from "node:fs/promises";
const text = await readFile(new URL("./config.json", import.meta.url), "utf8");
export const config = JSON.parse(text);
// server.mjs
import { config } from "./config.mjs";
console.log(config.port); // config.mjs finished loading before this line runsThe importing module waits for the awaited work to finish. That is convenient for loading config or opening a database connection once at startup.
The catch: a slow top-level await blocks every module that depends on it, so the app starts slower. If the promise rejects and nobody catches it, loading fails.
In CommonJS, top-level await is a syntax error. There you still need the async wrapper.
What to say in the interview
"Top-level await is available in ES modules only. It pauses that module's evaluation, and all modules importing it wait. I use it for one-time startup work like reading config, but not for slow, optional tasks."
Common mistakes
- Trying it in a
.jsfile when the project is CommonJS. - Awaiting many independent tasks one after another instead of using Promise.all.