What is a Promise? Pending, fulfilled and rejected
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
await delay(100);
console.log("ready");
A Promise starts pending, then may become fulfilled with a value or rejected with a reason. Both final states are settled. Resolving with another pending Promise adopts its eventual outcome, so resolved does not necessarily mean fulfilled. [1]
The executor passed to new Promise runs synchronously. Use the constructor to adapt callback-based APIs such as timers; do not wrap fetch in another Promise when it already returns one. [1]
Run examples with top-level await as ES modules (for example, an .mjs file).
Chaining then and catch: returning values
await Promise.resolve(21)
.then((value) => value * 2)
.then((value) => {
if (value > 40) {
throw new Error("Limit exceeded");
}
return value;
})
.catch((error) => console.log(error.message));
// Limit exceeded
Each then produces a new promise. A returned value becomes its result, a returned Promise is adopted, and a thrown error rejects it. Forgetting return when starting asynchronous work inside then can finish the step early and detach errors from the chain. [2]
The example transforms a number and then raises a validation error. The final catch handles failures from either step. Returning a fallback from catch recovers the chain; an empty catch can accidentally conceal a failure.
How async and await actually work
function withThen() {
return Promise.resolve(21).then((value) => value * 2);
}
async function withAwait() {
const value = await Promise.resolve(21);
return value * 2;
}
console.log(await withThen(), await withAwait()); // 42 42
An async function always returns a Promise, even when its return expression is a number or string. An exception rejects that promise. Await suspends the current function, not the entire application. Top-level await is available in ES modules, not classic scripts. [3][4]
Both functions in the example yield 42. Await is useful when a later step requires an earlier result. Adding async to CPU-intensive code does not move that code to a different thread.
Event loop: when does code after await run?
console.log("A");
setTimeout(() => console.log("D"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("B");
// A, B, C, D
In browsers, Promise reactions are scheduled as microtasks. Once the current call stack is empty, queued microtasks run before the next task, such as a timer callback. Await also defers continuation for an already available value. [4][5]
The example prints A, B, C, D. A zero-delay timer does not outrank then. An endless sequence of microtasks can delay rendering; consider a Web Worker for CPU-heavy work rather than adding more promises.
Promise.all vs allSettled vs any vs race
const success = Promise.resolve("profile");
const failure = Promise.reject(new Error("Unavailable"));
const results = await Promise.allSettled([success, failure]);
console.log(results.map((result) => result.status));
// ["fulfilled", "rejected"]
console.log(await Promise.any([failure, success])); // profile
Promise.all requires all operations to fulfill and preserves input order in the result; it rejects when an input rejects. allSettled waits for every input and returns a status with value or reason. [6][7]
Promise.any takes the first fulfillment or rejects with AggregateError if all inputs reject. race follows the first settlement, successful or not. None of these combinators cancels the remaining operations by itself. [8][9]
Use all for a dashboard that requires every result, allSettled for independent widgets, any for interchangeable data sources, and race when the first settlement is the desired outcome.
Sequential versus concurrent requests
async function sequential(getProfile, getOrders) {
const profile = await getProfile();
const orders = await getOrders(profile.id);
return { profile, orders };
}
async function concurrent(getProfile, getSettings) {
const [profile, settings] = await Promise.all([
getProfile(),
getSettings(),
]);
return { profile, settings };
}
If a profile ID is needed to retrieve orders, the calls are dependent. If profile and settings are independent, start both and immediately aggregate their promises with Promise.all. Passing function references instead does not invoke them. [6]
Two independent operations taking 300 ms each would ideally take around 600 ms sequentially and 300 ms concurrently, excluding overhead and resource constraints. This is an illustrative latency model, not a network benchmark or proof of parallel JavaScript execution.
Fetch API: HTTP 404 does not reject the Promise
async function getJSON(url, options = {}) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
Fetch normally fulfills when response headers arrive, even for HTTP 404 or 500. Network failures and cancellation can reject it. Check response.ok (status 200 through 299) before consuming data. [10]
response.json is also asynchronous and can fail, for example if a server returns HTML instead of JSON. The getJSON example assumes an endpoint contract with a JSON response; handle 204 No Content separately. Validating the decoded data's shape is another responsibility.
Cancel fetch and enforce a timeout
async function getJSONWithTimeout(url, ms = 5000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
return await getJSON(url, { signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
Promises have no universal cancel method. Fetch accepts an AbortController signal; abort can interrupt a request and response body consumption. Do not reuse an already aborted signal for a new request. [11]
The example creates a controller and clears the timeout in finally, even if the request fails. The deadline covers the request and JSON reading but cannot guarantee exact timing if the thread is blocked. Client-side cancellation does not undo work already performed by the server.
This example uses getJSON from section 7. The /api paths are illustrative endpoints of your own API.
Live search: preventing stale responses
function createSearch({ render, showError, setLoading }) {
let sequence = 0;
let controller;
async function search(query) {
const id = ++sequence;
controller?.abort();
const current = new AbortController();
controller = current;
setLoading(true);
try {
const url = `/api/search?q=${encodeURIComponent(query)}`;
const results = await getJSON(url, { signal: current.signal });
if (id === sequence) {
render(results);
}
} catch (error) {
if (id === sequence && !current.signal.aborted) {
showError(error);
}
} finally {
if (id === sequence) {
setLoading(false);
}
}
}
function dispose() {
++sequence;
controller?.abort();
controller = undefined;
setLoading(false);
}
return { search, dispose };
}
When users type successive queries, an older response may arrive later and overwrite the newer results. Debouncing reduces request count but does not solve this race. The example aborts the previous request and additionally checks an execution ID before updating state.
Apply the same ID check to error handling and loading indicators, otherwise older work can hide the newer loading state. Call dispose when the component is destroyed. The pattern is framework-independent and can be connected to React, Angular or plain DOM code.
This example uses getJSON from section 7. The /api paths are illustrative endpoints of your own API.
Async loops: forEach, map and concurrency limits
async function processSequentially(items, save) {
for (const item of items) {
await save(item);
}
}
async function loadInBatches(items, load) {
const results = [];
for (let i = 0; i < items.length; i += 4) {
const batch = items.slice(i, i + 4);
results.push(...(await Promise.all(batch.map((item) => load(item)))));
}
return results;
}
forEach does not wait for promises returned by its callback. Use for...of with await for dependent operations, and Promise.all with map for a small set of independent operations. [12]
Avoid firing thousands of requests at once. The example runs batches of four and starts the next batch after the current one completes. This is a simple limit, but one slow item delays the next batch. Larger queues benefit from worker pools and API rate-limit handling, such as HTTP 429.
Error handling, finally and responsibility boundaries
async function loadProfile({ setLoading, showError }) {
setLoading(true);
try {
return await getJSON("/api/profile");
} catch (error) {
showError(error);
throw error;
} finally {
setLoading(false);
}
}
Use await inside try/catch when the local handler must catch a returned operation's rejection. Simply returning a promise from try does not catch its later rejection. Finally handles cleanup, but a cleanup error can replace the original failure. [3][13]
Catch errors where you can make a decision: display feedback, restore state or retry a safe read. Do not automatically retry writes without an idempotency guarantee. The example resets loading without converting a failure into apparent success.
This example uses getJSON from section 7. The /api paths are illustrative endpoints of your own API.
