Top-Level await
Modules can await outside any function, which changes how a module loads and what that means for everything importing it.
Top-level await works in ES modules only. A module that uses it becomes asynchronous, and every module importing it waits for it to finish. That is useful for setup and dangerous for anything slow or optional.
EXERCISE
1await Without a Function
In a module, await works at the top level, and the module itself becomes the thing that is awaited.
It works, but only in a module:
// config.js (an ES module)
const response = await fetch("/api/config");
export const config = await response.json();
No wrapping function, no immediately-invoked async expression. This is valid in any file loaded as a module: a <script type="module">, a .mjs file, or a .js file in a package with "type": "module".
In a classic script it is a syntax error:
// <script src="app.js"> without type="module"
// const data = await fetch("/api");
// SyntaxError: await is only valid in async functions and
// the top level bodies of modules
Which replaced a pattern you will still see:
// The old workaround: an immediately-invoked async function
(async () => {
const response = await fetch("/api/config");
const config = await response.json();
start(config);
})();
// Today, in a module:
const response = await fetch("/api/config");
const config = await response.json();
start(config);
The wrapper existed only to create a function that await was allowed in. With top-level await it is unnecessary, and its disappearance is one of the clearer readability wins in modern .
What it actually does: the module becomes asynchronous.
// config.js
console.log("config: start");
export const config = await loadConfig(); // takes 500ms
console.log("config: done");
// app.js
import { config } from "./config.js";
console.log("app: running with", config.env);
// config: start
// config: done
// app: running with production
app.js did not run until config.js had finished. The import waited. That is the whole feature: a module with a top-level await is not considered loaded until its awaits complete, and anything importing it is held back.
Which is genuinely useful for real setup:
// db.js
const connection = await connectToDatabase();
export { connection };
// Anything importing this gets a connection that is ready,
// with no initialisation check and no "not connected yet" state.
Before this, the usual shape was exporting a promise and making every caller await it, or exporting an init() that everyone had to remember to call. Top-level await removes both.
The right use is something the whole module genuinely cannot function without: a configuration file, a connection, a WebAssembly module. If the rest of the module could do useful work while it loads, the await belongs inside a function instead, because at the top level it holds up every importer as well.
EXERCISE
2What It Costs, and Where It Bites
Blocking every importer is the point of the feature and also its main hazard.
The cost is transitive:
// slow.js
export const data = await fetchSomethingSlow(); // 3 seconds
// middle.js
import { data } from "./slow.js";
export const derived = transform(data);
// app.js
import { derived } from "./middle.js";
app.js waits three seconds, and nothing in app.js mentions slow.js. A top-level await anywhere in the import graph delays everything downstream of it, which makes it a decision about your whole application rather than about one file.
Independent modules still load in parallel:
// Both of these await at the top level.
import { a } from "./a.js"; // 1 second
import { b } from "./b.js"; // 1 second
// Total is about 1 second, not 2. They are fetched and evaluated
// concurrently; only their awaits are joined before the importer runs.
So the cost is the slowest branch, not the sum. Still worth knowing which branch is slowest.
A circular import with top-level await deadlocks:
// a.js
import { b } from "./b.js";
export const a = await something();
// b.js
import { a } from "./a.js";
export const b = await somethingElse();
// Each waits for the other. Neither finishes.
Circular imports are tolerable without top-level await, because the bindings are hoisted and filled in later. With it, each module genuinely cannot complete until the other does. Unit 8 covers circular dependencies in general.
The usual alternative for anything optional:
// Instead of holding up every importer:
export async function getConfig() {
const response = await fetch("/api/config");
return response.json();
}
// The caller decides when to pay the cost:
const config = await getConfig();
Exporting a function rather than an awaited value keeps the module synchronous and moves the decision to whoever needs the value. This is the eager-versus-lazy point from Unit 5, applied at module scope.
And dynamic import pairs naturally with it:
if (user.prefersHeavyFeature) {
const { heavyThing } = await import("./heavy.js");
heavyThing();
}
The module is fetched only if that branch runs, so a slow module costs nothing to anyone who does not need it. Unit 8 covers import() properly.
Pro Tip: Before adding a top-level await, ask whether every future importer should pay for it. For a database connection the answer is usually yes. For anything optional, slow, or only needed on one route, export an async function instead and let the caller choose, because once it is at module scope that choice is gone.
EXERCISE
3Three Ways to Initialise a Module
Top-level await is one answer to module setup, and comparing it against the alternatives makes the trade-off concrete.
Every module that needs something ready before it can work faces the same choice. There are three shapes, and each is right somewhere.
One: top-level await. Eager, and everyone waits.
// db.js
export const connection = await connectToDatabase();
Importers get a ready connection with no checks. Nobody can forget to initialise, and nobody can use it too early. The cost is that every importer waits, even ones that never touch the database on that request.
Use when the module is genuinely required for the application to function at all.
Two: an exported async function. Lazy, and the caller decides.
// config.js
export async function getConfig() {
const response = await fetch("/api/config");
return response.json();
}
Nothing happens at import. The cost lands on whoever calls it, at the moment they call it. The trade is that callers must remember to await, and repeated calls repeat the work unless you add .
Use when the value is optional, slow, or only needed on some paths.
Three: a cached lazy getter. Lazy once, then instant.
// config.js
let cached = null;
export function getConfig() {
if (!cached) {
cached = fetch("/api/config").then((r) => r.json());
}
return cached;
}
The first caller starts the work; every later caller gets the same promise. Note what is cached is the promise, not the value, which means two simultaneous callers share one request rather than starting two.
That detail is the whole reason this pattern works. Caching the resolved value instead leaves a window where a second caller arrives before the first has finished and fires a duplicate request.
Side by side:
// top-level await ready on import, everyone pays, cannot be misused
// async function nothing on import, caller pays each time, simplest
// cached getter nothing on import, first caller pays once, shared
And a fourth that looks tempting and is not:
// Do not export a value that is filled in later.
export let config = null;
fetch("/api/config").then((r) => r.json()).then((c) => {
config = c;
});
// Importers see null, sometimes, depending on timing.
This reintroduces exactly the "not ready yet" state the other three avoid, and the failure is intermittent, which is the worst kind.
Pro Tip: The cached getter is the one worth reaching for by default in application code. It costs nothing at import, deduplicates concurrent callers, and needs no coordination. Keep top-level await for the small number of things nothing can run without, and keep the plain async function for work that genuinely should happen fresh each time.
