Skip to content

JavaScript promises, async/await and modules

Two ideas shape how modern JavaScript programs are built. Asynchronous code lets one thread start slow work, such as a network request or a database query, and continue with other work until the result arrives. Modules split a program into files with explicit imports and exports. They meet in top-level await, which lets a module wait for asynchronous setup before the modules that import it run.

This page explains the four features in order: promises (ES2015), async functions and await (ES2017), ES modules (ES2015) and top-level await (ES2022). If the event loop is new to you, read Asynchronous code in the basics first.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). For multi-file samples, save the files in one folder with the names shown in their first-line comments and run node main.mjs. The outputs shown were produced with Node.js 22.23. Network calls are simulated with timers so the samples run offline.

Feature Edition Use it when
Promises ES2015 You return or combine results that arrive later.
Async functions and await ES2017 You write sequential-looking code over promises with try/catch.
Modules ES2015 You split code into files with explicit dependencies.
Top-level await ES2022 A module must finish asynchronous setup before it is used.

Introduced in ECMAScript 2015. A promise is an object that stands for a result that is not available yet. It starts pending and settles exactly once, either fulfilled with a value or rejected with a reason (normally an Error). After it settles, its state never changes.

You create one with new Promise((resolve, reject) => { ... }); the executor function runs immediately and synchronously, and an exception thrown inside it rejects the promise. Most of the time you do not construct promises yourself: APIs such as fetch and fs/promises return them.

then(onFulfilled, onRejected) registers reactions and returns a new promise, which is what makes chaining work. Whatever a reaction returns becomes the next promise’s value; if it returns a promise, the chain waits for it; if it throws, the next promise is rejected and the error skips forward to the nearest catch. finally (ES2018) runs clean-up without changing the result. Reactions always run asynchronously, as microtasks, even for promises that are already settled.

The static combinators run several promises at once: Promise.all (fulfills with all values or rejects on the first failure), Promise.allSettled (ES2020, reports every outcome), Promise.any (ES2021, first success) and Promise.race (first to settle, success or failure).

const wait = (ms, value, fail = false) =>
new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
function loadOrder(id) {
return wait(30, { id, customerId: "C-7", total: 37 });
}
await loadOrder("A-1001")
.then((order) => {
console.log("1. loaded", order.id);
return wait(20, { ...order, customer: "Ana" }); // a returned promise is awaited by the chain
})
.then((order) => {
console.log("2. enriched", order.customer);
if (order.total < 50) throw new Error("Below minimum for free shipping");
return order;
})
.then(() => console.log("never runs"))
.catch((error) => console.log("3. caught:", error.message))
.finally(() => console.log("4. finally: hide spinner"));
const results = await Promise.allSettled([
wait(10, "stock ok"),
wait(15, "payment provider timeout", true),
wait(5, "address ok"),
]);
console.log(results.map((r) => (r.status === "fulfilled" ? r.value : `failed: ${r.reason.message}`)));
try {
await Promise.all([wait(10, "stock ok"), wait(15, "payment provider timeout", true)]);
} catch (error) {
console.log("Promise.all rejected:", error.message);
}
console.log("first success:", await Promise.any([wait(20, "mirror-b"), wait(10, "mirror-a down", true), wait(15, "mirror-a2")]));

Output:

1. loaded A-1001
2. enriched Ana
3. caught: Below minimum for free shipping
4. finally: hide spinner
[ 'stock ok', 'failed: payment provider timeout', 'address ok' ]
Promise.all rejected: payment provider timeout
first success: mirror-a2

Pitfalls:

  • Forgetting to return inside then. A reaction that starts another promise without returning it breaks the chain: the next step runs too early and errors escape.
  • No catch at the end of a chain. An unhandled rejection terminates a Node.js process by default (since Node.js 15). End every chain with catch or await it in try/catch.
  • Wrapping promises in new Promise. new Promise((resolve) => fetchX().then(resolve)) loses rejections. Return the existing promise instead.

Introduced in ECMAScript 2017. An async function always returns a promise: a returned value fulfills it and a thrown error rejects it. Inside, await expression pauses the function until the promise settles, then resumes with the value, or throws the rejection reason at that line. Only that function pauses; the event loop keeps running other code. Awaiting a non-promise value simply continues on the next microtask.

This lets asynchronous code read like synchronous code and use ordinary try/catch/finally, loops and conditionals. The cost is that it also makes it easy to wait sequentially when the operations are independent. Two await lines in a row take the sum of both durations; start both first and await Promise.all to take the maximum.

Things to know:

  • await works inside async functions, and at the top level of ES modules (see Top-level await).
  • Inside try, write return await promise if you want the catch or finally of that function to see a rejection; a plain return promise leaves the function before the promise settles.
  • Array methods such as forEach and map do not wait for async callbacks. Use for...of with await for sequential work, or Promise.all(items.map(async ...)) for parallel work.
  • For a stream of values that arrive over time, use for await...of with async iterables (ES2018).
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const started = Date.now();
const elapsed = () => `${Math.round((Date.now() - started) / 50) * 50}ms`;
async function getCustomer(id) {
await wait(100);
return { id, name: "Ana" };
}
async function getOrders(customerId) {
await wait(100);
if (customerId === "C-404") throw new Error(`No customer ${customerId}`);
return [{ id: "A-1001", total: 37 }];
}
async function dashboardSequential(id) {
const customer = await getCustomer(id);
const orders = await getOrders(id); // waits for the first call to finish
return `${customer.name}: ${orders.length} order(s)`;
}
async function dashboardParallel(id) {
const [customer, orders] = await Promise.all([getCustomer(id), getOrders(id)]);
return `${customer.name}: ${orders.length} order(s)`;
}
console.log(await dashboardSequential("C-7"), "after", elapsed());
const mark = Date.now();
console.log(await dashboardParallel("C-7"), "after another", `${Math.round((Date.now() - mark) / 50) * 50}ms`);
async function safeDashboard(id) {
try {
return await dashboardParallel(id); // await so this catch sees the rejection
} catch (error) {
return `fallback view (${error.message})`;
}
}
console.log(await safeDashboard("C-404"));
const pending = getCustomer("C-8");
console.log("an async function returns:", Object.prototype.toString.call(pending));
const ids = ["A-1", "A-2", "A-3"];
const saved = [];
ids.forEach(async (id) => {
await wait(10);
saved.push(id);
});
console.log("forEach did not wait:", saved.length);
for (const id of ids) {
await wait(10);
saved.push(id);
}
console.log("for...of waited:", saved.length);

Output:

Ana: 1 order(s) after 200ms
Ana: 1 order(s) after another 100ms
fallback view (No customer C-404)
an async function returns: [object Promise]
forEach did not wait: 0
for...of waited: 6

The forEach callbacks finish shortly afterwards, which is why the final count is 6 rather than 3: their work happened, but nothing waited for it or would have seen their errors.

Pitfalls:

  • Accidental sequential awaits. Independent calls awaited one after another add their latencies. Start them together and await Promise.all.
  • async callbacks in forEach. Nothing waits for them and their rejections are unhandled. Use for...of or Promise.all.
  • Unbounded parallelism. Promise.all(10000 calls) can overload a database or API. Process in batches or use a concurrency limit.

Introduced in ECMAScript 2015. An ES module is a file whose top-level names are private unless exported. export makes a function, class or value available; import brings it in. A module can have many named exports (export function quote() {}, imported as import { quote } from "./pricing.mjs") and at most one default export (imported without braces under any name). import * as pricing imports the whole namespace object, and export { x } from "./y.mjs" re-exports.

Rules that affect real code:

  • Static structure: import and export declarations must be at the top level. Tools can see the dependency graph without running code, which enables tree-shaking. For conditional or on-demand loading, use import().
  • Live, read-only bindings: an import is a view of the exporting module’s variable. If the exporter changes it, importers see the change; assigning to an import throws a TypeError.
  • Evaluated once: each module runs a single time per realm, and every importer shares the same instance, which makes modules natural singletons.
  • Strict mode and own scope: modules are always strict, and top-level this is undefined.
  • Loading: in browsers, <script type="module"> is deferred and needs full relative paths with extensions. In Node.js, files ending in .mjs, or .js files in a package with "type": "module", are ES modules, and relative imports need the file extension.
pricing.mjs
export const currency = "EUR";
export let quotesIssued = 0;
export function quote(lines) {
quotesIssued++;
return lines.reduce((sum, line) => sum + line.price * line.qty, 0);
}
export default function formatPrice(amount) {
return `${amount.toFixed(2)} ${currency}`;
}
main.mjs
import formatPrice, { quote, quotesIssued, currency } from "./pricing.mjs";
import * as pricing from "./pricing.mjs";
const lines = [{ price: 9.5, qty: 2 }, { price: 18, qty: 1 }];
console.log("before:", quotesIssued);
console.log(formatPrice(quote(lines)));
console.log("after (live binding):", quotesIssued, "| namespace:", pricing.quotesIssued);
console.log(Object.keys(pricing), currency, typeof this);
try {
quotesIssued = 10;
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

before: 0
37.00 EUR
after (live binding): 1 | namespace: 1
[ 'currency', 'default', 'quote', 'quotesIssued' ] EUR undefined
TypeError: Assignment to constant variable.

Pitfalls:

  • Missing file extensions. import "./pricing" fails in browsers and Node.js ES modules. Write ./pricing.mjs or ./pricing.js.
  • Circular imports. Two modules importing each other can see bindings that are still in the temporal dead zone. Move shared code into a third module.
  • Mixing module systems. CommonJS (require, module.exports) and ES modules interoperate in Node.js only with restrictions. Pick ES modules for new code.

Introduced in ECMAScript 2022. Top-level await lets an ES module use await outside any function. The module’s evaluation pauses at that point, and every module that imports it, directly or indirectly, waits until it has finished before running its own body. Modules that do not depend on it can continue to evaluate. It works only in modules: in a classic script or a CommonJS file, await at the top level is a syntax error.

Typical uses are loading configuration or a dependency before exports are used, choosing an implementation with a dynamic import() fallback, and short scripts and command-line tools, where wrapping everything in an async function main() adds nothing.

Because it blocks importers, top-level await in a widely imported module delays the whole application’s start, and a rejection makes the module, and everything that imports it, fail to load. In Node.js 22, a module graph that contains top-level await cannot be loaded with require(); it throws ERR_REQUIRE_ASYNC_MODULE, and you must use import() instead. If a top-level promise never settles, Node.js exits with code 13 and an “unsettled top-level await” warning.

config.mjs
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log("config: loading");
await wait(50); // stands in for reading a secrets store or remote config
export const config = { apiBase: "https://api.example.test", pageSize: 25 };
console.log("config: ready");
main.mjs
import { config } from "./config.mjs";
console.log("main: runs only after config.mjs has finished");
console.log(config.apiBase, config.pageSize);
let format;
try {
({ default: format } = await import("./currency-format.mjs"));
} catch {
format = (amount) => `${amount} EUR`; // optional module missing: fall back
}
console.log(format(37));

Output:

config: loading
config: ready
main: runs only after config.mjs has finished
https://api.example.test 25
37 EUR

Pitfalls:

  • Slow awaits in shared modules. Every importer waits. Keep long or failure-prone work inside functions that callers invoke when they need it.
  • Rejections at load time. An unhandled rejection at the top level makes the module fail and the import throw. Catch and fall back when the dependency is optional.
  • Using it in CommonJS or classic scripts. It is only valid in ES modules (.mjs, "type": "module", or <script type="module">).
Situation Prefer
Several steps that depend on each other async function with sequential await
Independent requests Start them together, then await Promise.all
Some requests may fail and you want every result Promise.allSettled
The first available mirror or cache wins Promise.any
Splitting code into files ES modules with named exports
Loading code only when needed Dynamic import()
A module that needs async setup before use Top-level await, kept short
A library imported by many modules Avoid top-level await; export an async init() instead

1. What are the states of a promise, and what does then return? Pending, then fulfilled or rejected, settled once. then returns a new promise resolved with whatever the reaction returns (adopting it if it is a promise) or rejected if the reaction throws.

2. What is the difference between Promise.all, Promise.allSettled, Promise.any and Promise.race? all fulfills with every value or rejects on the first rejection; allSettled waits for all and reports each outcome; any fulfills with the first success and rejects with an AggregateError if all fail; race settles like the first promise to settle.

3. Why does return promise inside try not trigger the function’s catch? The function returns the promise immediately and the try block is finished before the promise rejects. return await promise keeps the function inside the try until it settles.

4. What is a live binding in ES modules? An imported name refers to the exporting module’s variable, not a copy of its value. If the exporter reassigns it, importers see the new value; importers cannot assign to it.

5. How does top-level await affect module loading? The module’s evaluation pauses, and every module that depends on it waits; independent modules continue. A rejection fails the module and its importers. In Node.js 22, require() of such a graph throws ERR_REQUIRE_ASYNC_MODULE.

6. Senior scenario: an order dashboard API makes eight independent calls with sequential awaits and responds in 1.6 seconds. A colleague proposes Promise.all over all eight. What do you check before and after the change? Confirm the calls are truly independent and safe to run at the same time; for example, some may share a database connection pool or rate limit. Decide the failure policy: Promise.all fails the whole response on one error, while allSettled lets the page render partial data. Add timeouts with AbortSignal.timeout() so one slow dependency does not hold the response, and cap concurrency if the list of calls grows with the data. Measure p95 latency and downstream load after the change, not just the average.

  1. Promise.prototype.finally: clean-up that runs on success and failure.
  2. Promise.allSettled and Promise.any: the ES2020 and ES2021 combinators in depth.
  3. Async iteration: for await...of, async generators and streams.
  4. Dynamic import(): loading modules on demand, import attributes and code splitting.
  5. Error cause: keeping the original error when you rethrow.
  6. Shared memory and Atomics: real parallelism with workers.