A promise in JavaScript is an object representing a value you do not have yet: the eventual result of an asynchronous operation such as a network request, a file read, or a timer. It starts pending and settles exactly once, either fulfilled with a value or rejected with an error. async/await is the modern syntax for reading it.
This guide covers the states, .then/.catch/.finally, async/await and its error handling, then the practical jobs: choosing between Promise.all, allSettled, race and any, limiting how many promises run at once, sleeping and polling, debounce and throttle, what an async function really is under the hood, and the promise mistakes I flag most in code review.
The three states (and "settled")
Every promise is in exactly one of three states:
- pending: the work has not finished. This is the starting state.
- fulfilled: the work finished successfully and the promise has a value.
- rejected: the work failed and the promise has a reason (usually an
Error).
A promise that is no longer pending (fulfilled or rejected) is called settled. The transition is one-way and one-time: a pending promise settles exactly once, and after that its state and value never change. You cannot un-reject a promise or resolve it twice; the second attempt is silently ignored. That immutability is the whole point. Once you hold a settled promise, reading it is safe forever.
.then, .catch, .finally
You read a promise's eventual value with three methods:
fetch("https://api.example.com/user/42")
.then((response) => response.json()) // runs on fulfilment, returns the next promise
.then((user) => console.log(user.name))
.catch((error) => console.error("request failed:", error)) // runs on any rejection above
.finally(() => console.log("done, success or not")); // always runs, gets no valueThree things worth internalising:
.then()returns a new promise. Whatever youreturnfrom inside it becomes the value the next.then()receives. Return a promise (likeresponse.json()) and the chain waits for it to settle before continuing. This is how you sequence asynchronous steps without nesting..catch(fn)is shorthand for.then(undefined, fn). A single.catch()at the end of a chain handles a rejection from any step above it, because a rejection skips every.then()until it finds a rejection handler. One catch covers the whole chain..finally()runs on both outcomes and receives no argument. Use it for cleanup (hide a spinner, close a handle). It does not swallow a rejection: if the promise rejected, it still rejects after.finally()runs, so a downstream.catch()is still required..finally()is for side effects, not error handling.
async/await is the default now
The chain above reads top-to-bottom once you rewrite it with async/await, which is the syntax I reach for first in 2026:
async function teLoadUser(id) {
const response = await fetch(`https://api.example.com/user/${id}`);
const user = await response.json();
return user.name;
}await pauses the function until the promise settles, then unwraps its value (or throws its rejection). It does not block the thread; JavaScript is single-threaded, and while one async function is suspended at an await, the event loop keeps doing other work. Two facts that surprise people:
- An
asyncfunction always returns a promise. Evenasync function f() { return 1; }returns a promise that fulfils with1, never the bare1. If youreturna promise from an async function, it is not double-wrapped; the outer promise adopts the inner one's eventual value. - You can
awaita non-promise.await 5just gives you5.awaitwraps its operand inPromise.resolve(), so awaiting a value-or-promise always works. That is why you almost never need to check whether something is a promise before awaiting it.
Why both of those are true falls out of what the engine does with an async function, covered in how async functions work internally.
Error handling: try/catch around await
With .then() chains you handle errors in .catch(). With await, you use ordinary try/catch, which is one of its biggest wins: synchronous and asynchronous errors land in the same block.
async function teLoadUser(id) {
try {
const response = await fetch(`https://api.example.com/user/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`); // fetch does NOT reject on 4xx/5xx
}
return await response.json();
} catch (error) {
console.error("could not load user:", error);
return null; // or rethrow, depending on the caller
}
}Note the return await response.json() inside the try: if you write return response.json() (no await), the function returns before the JSON promise settles, so a rejection from parsing escapes the try/catch and becomes an unhandled rejection in the caller. Inside a try block, return await is the safe form.
One thing to take seriously: an unhandled rejection crashes a modern Node process. Since Node 15 the default behaviour is --unhandled-rejections=throw, so a promise that rejects with no .catch() and no try/catch terminates the program. A floating fetch() with no error handling is a latent crash, not a warning. The common promise mistakes section below has the full list, floating promises included.
Don't wrap something that already returns a promise
This is the antipattern I correct most often. The new Promise(...) constructor exists to adopt a callback-based API into the promise world. It is the wrong tool when the thing you are wrapping already returns a promise.
// Antipattern: pointless wrapper around an already-async call
function teGetUser(id) {
return new Promise((resolve, reject) => {
fetch(`/user/${id}`)
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
// Correct: fetch already returns a promise. Just return it.
function teGetUser(id) {
return fetch(`/user/${id}`);
}The wrapper adds nothing but a layer where errors can leak (forget the .catch and the rejection is swallowed) and a new place for bugs. Reserve new Promise for genuinely callback-based primitives that have no promise interface, like setTimeout or an old-style event:
// Legitimate use: setTimeout has no promise interface, so we build one.
const teSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await teSleep(1000);(In Node you do not even need that wrapper: import { setTimeout } from "node:timers/promises" gives you an awaitable await setTimeout(1000) directly. More patterns in sleep, wait, and poll below.)
The await-in-a-loop trap: sequential vs parallel
This is the single most common async/await performance bug. Awaiting inside a for loop runs the operations one after another, each waiting for the previous to finish:
// SLOW: each fetch waits for the one before it. Three 200ms requests = ~600ms.
async function teLoadAllSequential(ids) {
const users = [];
for (const id of ids) {
users.push(await fetch(`/user/${id}`).then((r) => r.json()));
}
return users;
}If the requests do not depend on each other, that serialization is wasted time. Kick them all off first, then await them together with Promise.all:
// FAST: all three fetches start at once. Total time = the slowest one, ~200ms.
async function teLoadAllParallel(ids) {
const requests = ids.map((id) => fetch(`/user/${id}`).then((r) => r.json()));
return Promise.all(requests); // resolves to an array of results, in input order
}The trap is subtle because both versions are correct; one is just three times slower. The rule of thumb: if iteration n does not need the result of iteration n-1, do not await inside the loop. Build an array of promises and hand it to a combinator. Promise.all rejects as soon as any one input rejects (fail-fast); when you want every result regardless of individual failures, reach for Promise.allSettled. The full decision guide is in the combinators section below. And when the array is large (hundreds or thousands of requests), going fully parallel is its own bug: cap it with a promise pool.
A related caution: Array.prototype.forEach does not await an async callback. arr.forEach(async (x) => { await something(x); }) fires every callback and moves on without waiting for any of them. Use for...of with await (sequential) or Promise.all(arr.map(...)) (parallel) instead.
Promise.all vs allSettled vs race vs any
JavaScript gives you four ways to combine an array of promises, and the right one depends entirely on how you want failure handled:
Promise.allwaits for every promise, but rejects the moment any one rejects. All-or-nothing.Promise.allSettledwaits for every promise and never rejects; you get an array of outcomes, each marked fulfilled or rejected.Promise.racesettles as soon as the first promise settles, whether that is a fulfillment or a rejection.Promise.anysettles as soon as the first promise fulfills, ignoring rejections; it rejects only if all of them reject.
| Combinator | Settles when | Rejects when | Fulfillment value |
|---|---|---|---|
Promise.all | all promises fulfill | the first rejection (short-circuits) | array of fulfillment values, in input order |
Promise.allSettled | every promise has settled | never | array of outcome objects (status plus value or reason) |
Promise.race | the first promise settles | first settle is a rejection | the first settled value |
Promise.any | the first promise fulfills | all reject (with AggregateError) | the first fulfillment value |
Note the symmetry: all and race reject on the first rejection; allSettled and any are the failure-tolerant pair.
Promise.all: fail fast
Reach for all when a single failure makes the whole operation invalid, such as three API calls that feed one render. The destructuring works because all preserves input order regardless of which promise resolved first. The examples in this section use two small helpers, a JSON fetch that rejects on HTTP errors and a promise that rejects after a delay:
async function teFetchJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
return res.json();
}
const teTimeout = (ms) =>
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms)
);
const [user, orders, settings] = await Promise.all([
teFetchJson("/api/user"),
teFetchJson("/api/orders"),
teFetchJson("/api/settings"),
]);The instant one promise rejects, the returned promise rejects with that reason, and you lose the values from the others even if they already resolved. The other promises are not cancelled (JavaScript has no cancellation here); they keep running and their results are discarded.
Promise.allSettled: keep every outcome
allSettled waits for every promise to settle and resolves to an array where each entry is either {status: "fulfilled", value} or {status: "rejected", reason}. Use it when tasks are independent: send five notifications, warm a batch of caches. One failure should not throw away the four that worked.
const results = await Promise.allSettled([ok1, willReject, ok2]);
const succeeded = results.filter(r => r.status === "fulfilled").map(r => r.value);
const failed = results.filter(r => r.status === "rejected").map(r => r.reason);Two gotchas. A trailing .catch on allSettled is dead code, because there is never a rejection to catch; the errors live on each entry's reason. And if you still carry the pre-allSettled hack Promise.all(tasks.map(p => p.catch(() => undefined))), retire it: it collapses a genuine TypeError into undefined, indistinguishable from a legitimately empty result, while allSettled keeps the reason.
Promise.race: first to settle, win or lose
race settles with the first promise to settle. People expect "first one to succeed", and that is the trap: if the first promise to settle rejects, race rejects, even if every other promise would have fulfilled. The canonical legitimate use is a timeout:
const data = await Promise.race([
teFetchJson("/api/slow"),
teTimeout(5000), // rejects after 5s
]);For a real network timeout, AbortSignal.timeout() is cleaner and actually cancels the request; see adding a timeout to fetch with AbortController.
Promise.any: first success, AggregateError if all fail
any resolves with the first fulfillment and ignores rejections. It rejects only when every promise has rejected, with an AggregateError whose .errors array holds every reason. That is the redundancy pattern: query several equivalent mirrors and take whichever answers first.
try {
const fastest = await Promise.any([
teFetchJson("https://mirror-a.example/file"),
teFetchJson("https://mirror-b.example/file"),
teFetchJson("https://mirror-c.example/file"),
]);
} catch (err) {
// Only reached if ALL mirrors failed. err.errors is the array of reasons.
console.error("all mirrors down", err.errors);
}Runtime support
Promise.all and Promise.race are original ES2015. Promise.allSettled landed in Node 12.9.0 (August 2019) and in evergreen browsers around the same time. Promise.any and AggregateError shipped with V8 8.5 in Chrome 85 and Node 15, both in late 2020. All four are available in current browsers and any supported Node release with no polyfill.
Limit concurrent promises
Promise.all(items.map(fn)) does not throttle anything. The work starts the moment each promise is created, so items.map(fn) launches every task in the same tick, before Promise.all even sees the array. Ten thousand URLs means ten thousand fetch calls at once, and that fans out into real failures: HTTP 429 from rate-limited APIs, socket and file-descriptor exhaustion (EMFILE in Node; in the browser, requests stall behind the per-host connection cap), every response buffer held in memory at once, and a synchronized burst that looks like an attack on the server you depend on.
The fix is a promise pool: a fixed number of workers pulling from a shared queue, so at most N tasks run at once and the next starts only when a slot frees up. Dependency-free:
async function teMapLimit(items, limit, fn) {
const results = new Array(items.length);
let cursor = 0;
async function teWorker() {
while (cursor < items.length) {
const index = cursor++; // claim a slot, then release the loop
results[index] = await fn(items[index], index);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, teWorker);
await Promise.all(workers);
return results;
}
const bodies = await teMapLimit(urls, 5, async (url) => {
const res = await fetch(url);
return res.text();
});How the pool works
The workers share one mutable cursor instead of being handed fixed slices. Each worker reads it and increments it in one expression (cursor++), and because JavaScript is single-threaded that read-and-increment is atomic, so no two workers claim the same index. When a worker awaits fn(...) it yields the event loop and the others claim their own indices, which is what produces up to limit tasks in flight. When the queue is empty each worker's loop exits, and Promise.all(workers) resolves.
Results land at results[index], so the output matches input order, the same contract Promise.all gives you. A self-draining queue also balances uneven work: a worker that finishes a fast task grabs the next index instead of idling. Like Promise.all, this version rejects on the first error. To run everything and collect failures, have fn catch its own errors or use Promise.allSettled semantics.
Cancel the pool with AbortSignal
Check a signal before claiming each task, and pass it down so in-flight fetch calls abort too:
async function teMapLimit(items, limit, fn, { signal } = {}) {
const results = new Array(items.length);
let cursor = 0;
async function teWorker() {
while (cursor < items.length) {
signal?.throwIfAborted(); // stop claiming new work once aborted
const index = cursor++;
results[index] = await fn(items[index], index, signal);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, teWorker);
await Promise.all(workers);
return results;
}
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]);
await teMapLimit(urls, 5, (url, _i, sig) => fetch(url, { signal: sig }), { signal });AbortSignal.timeout and AbortSignal.any are available in modern browsers and in Node.js: timeout since 17.3 (backported to 16.14) and any since 20.3 (backported to 18.17).
p-limit and p-map
For production I usually reach for a maintained package that already handles the edge cases (empty input, a mapper that throws synchronously, abort). p-limit is the minimal primitive: wrap each call as limit(() => fetch(url)) and compose with your own Promise.all. p-map is the direct teMapLimit analog, pMap(items, mapper, { concurrency: 5 }), with stopOnError: false (reject with an AggregateError of all failures) and a signal option; it is the one I default to. @ricokahler/pool is another small zero-dependency option. As for the limit itself: match a rate-limited API's documented limit (often 5 to 20 in flight), start conservative, and raise it only if the downstream tolerates it.
Sleep, wait, and poll in JavaScript
JavaScript has no blocking sleep(). The language is single-threaded, so a function that froze the thread for two seconds would freeze the whole page (or the whole Node event loop) with it. Instead you schedule a timer and await it, the same one-liner as earlier:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function te_run() {
console.log("start");
await sleep(2000); // pauses THIS function for 2s, frees the thread meanwhile
console.log("2 seconds later");
}await sleep(2000) suspends only the current async function; the UI stays responsive and other timers still fire. People call the helper sleep, delay, or wait interchangeably. Do not ship the busy-wait version (while (Date.now() < end) {}): it pegs a core and freezes everything for the full duration.
Node.js: timers/promises
In Node you can skip the wrapper. node:timers/promises ships a promise-returning setTimeout, stable since Node 16 (it landed in 15.0). The import shadows the global setTimeout, so alias it if you still need the callback form. It also takes an AbortSignal, so a pending wait can be cancelled:
import { setTimeout as sleep } from "node:timers/promises";
await sleep(1000); // wait 1 second
const value = await sleep(1000, "done"); // resolves to "done" after 1s
const ac = new AbortController();
sleep(60_000, undefined, { signal: ac.signal })
.then(() => console.log("woke up"))
.catch(err => {
if (err.name === "AbortError") console.log("cancelled");
});
ac.abort(); // the pending sleep rejects with AbortError instead of hangingWait for a condition (polling)
More often you want to wait until something becomes true: an element appears, a flag flips, a job finishes. With no event to await, you poll with a hard deadline so you never spin forever:
async function teWaitFor(condition, { interval = 100, timeout = 5000 } = {}) {
const deadline = AbortSignal.timeout(timeout);
// await works for sync and async conditions alike
while (!(await condition())) {
if (deadline.aborted) {
throw new Error(`teWaitFor: condition not met within ${timeout}ms`);
}
await new Promise(resolve => setTimeout(resolve, interval));
}
}
// wait until a global is set, polling every 200ms, giving up after 10s
await teWaitFor(() => window.myWidget?.ready, { interval: 200, timeout: 10_000 });AbortSignal.timeout(ms) (Chrome 103 and Node 17.3 in 2022, Safari in 2024) aborts itself, so there is no stray timer to manage. Because the loop does await condition(), the condition can also be an async function (an HTTP probe, a DB ping); without that await, the returned promise is always truthy and the loop would exit on the first check. Polling is a fallback: if the thing can emit an event or hand you a promise, await that instead.
The only true block in JavaScript is Atomics.wait(), and the spec forbids it on a page's main thread; it works only inside a Web Worker or Node worker thread, as a SharedArrayBuffer coordination primitive, not a general pause.
setTimeout is not precise
Timers are best-effort. Per the HTML spec, once timers are nested five deep the browser clamps any delay below 4ms up to 4ms, which is why setTimeout(fn, 0) is a poor way to yield (queueMicrotask or a MessageChannel is faster). In a hidden tab, Chrome checks timers at most once per second, and since Chrome 88 intensive throttling drops a timer chain nested five deep to once per minute when the tab has been hidden over five minutes and silent for at least 30 seconds. For visual timing use requestAnimationFrame, and recompute against the clock rather than counting ticks.
To measure how long you actually waited, use performance.now(), not Date.now():
const t0 = performance.now();
await sleep(1000);
console.log(`waited ${performance.now() - t0} ms`); // e.g. 1001.3Date.now() is wall-clock time that can jump when the OS clock is corrected (NTP sync, a manual change, daylight saving), so subtracting two readings can give a negative or wrong duration. performance.now() is monotonic and high-resolution, and available globally in Node too. Rule of thumb: Date.now() for when, performance.now() for how long.
Debounce and throttle in JavaScript
A debounce makes a function wait until the calls stop coming before it runs. Wire it onto an event that fires too often (a keystroke, a resize, a scroll) and instead of running on every event it runs once, after a quiet gap you choose. It is built on the same setTimeout/clearTimeout pair as sleep, and you do not need Underscore or lodash for it; the whole thing is about ten lines:
function teDebounce(fn, wait, { leading = false } = {}) {
let timer;
const debounced = function (...args) {
const callNow = leading && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (!leading) fn.apply(this, args);
}, wait);
if (callNow) fn.apply(this, args);
};
debounced.cancel = () => {
clearTimeout(timer);
timer = null;
};
return debounced;
}
const onSearch = teDebounce((event) => {
fetchResults(event.target.value);
}, 300);
input.addEventListener("input", onSearch);Type "react", and fetchResults fires once, 300ms after you stop, with the value "react", not once per letter. Each call clears the previous timer and starts a new one, so as long as calls keep arriving inside the wait window, fn never runs; the moment a full wait passes with no new call, it runs with the most recent arguments. With leading: true it fires immediately on the first call and then ignores everything until the burst ends, which is what you want for a "save" button you do not want double-fired. Call onSearch.cancel() in a cleanup path (unmount, modal close, navigation) and any queued call is gone.
Cancel a debounce with AbortSignal
If your code already passes an AbortSignal around, wire the debounce to it instead of exposing your own method:
function teDebounce(fn, wait, { signal } = {}) {
let timer;
signal?.addEventListener("abort", () => clearTimeout(timer), { once: true });
return function (...args) {
clearTimeout(timer);
if (signal?.aborted) return; // already aborted: never schedule again
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
const controller = new AbortController();
const onSearch = teDebounce(handleSearch, 300, { signal: controller.signal });
// later, one abort() cancels the pending call and any fetch sharing the signal
controller.abort();One controller.abort() tears down the pending timer and any in-flight request that shares the signal, which kills the stale-response race that plagues search-as-you-type. The signal.aborted check matters too: without it, the next keystroke after the abort would schedule a fresh call against a signal that is already dead.
Debounce vs throttle
- Debounce: wait for quiet. Run once, after the events stop. Search-as-you-type (250 to 400ms), autosave (a second or two after the last edit), validating a field after the user finishes typing, expensive relayout on
window.resize. - Throttle: at most once per N ms. Run on a fixed cadence while events keep coming. A scroll position readout, a progress indicator, a drag handler, a scroll-linked analytics beacon.
Resize the window with a debounce and your relayout fires once, when you let go. Resize with a throttle and it fires every 200ms during the drag. Same event, opposite behavior. A throttle is a dozen lines:
function teThrottle(fn, interval) {
let last = 0;
let timer;
let lastArgs;
let lastThis;
return function (...args) {
lastArgs = args;
lastThis = this;
const now = Date.now();
const remaining = interval - (now - last);
if (remaining <= 0) {
clearTimeout(timer);
timer = null;
last = now;
fn.apply(this, args);
} else if (!timer) {
// trailing call so the final event isn't dropped
timer = setTimeout(() => {
last = Date.now();
timer = null;
fn.apply(lastThis, lastArgs);
}, remaining);
}
};
}It fires on the leading edge and guarantees a trailing call, so the last event in a burst is never lost (a common bug in naive throttles that only check elapsed time). Every call refreshes lastArgs/lastThis, so the trailing invocation runs with the most recent event, not the one that scheduled the timer.
requestAnimationFrame for scroll
If the throttled work is visual (painting, animating, reading layout), skip the millisecond interval and use requestAnimationFrame. It runs right before the next paint, so it is a throttle locked to the display's refresh rate:
let ticking = false;
window.addEventListener("scroll", () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
updateParallax(window.scrollY);
ticking = false;
});
});Keep the timer-based throttle for non-visual rate limiting (network calls, logging, analytics beacons).
Debounce in React and the this caveat
In React, useDeferredValue defers a low-priority re-render so the input stays responsive, but the re-render still happens, so it will not cut your network requests. A debounced value (a small custom hook, or useDebouncedValue from a utility library) holds back the state change itself, which is what reduces fetches. Debounce the value that triggers the network call, and defer the expensive render: debounce to cut requests, defer to cut jank.
The returned wrapper is a regular function, not an arrow, on purpose. An arrow captures this from where it is defined, so it cannot forward the call site's this through fn.apply(this, args). If your handler relies on this, keep the wrapper a regular function, or bind up front (teDebounce(this.handle.bind(this), 300)).
Top-level await in ES modules
You used to need an async wrapper just to use await at the top of a file. Since ES2022 you can await directly at module top level, with no enclosing function, in any ES module (a .mjs file, or a .js file in a package with "type": "module"):
// top of an ES module, no async wrapper needed
const config = await fetch("/config.json").then((r) => r.json());
export const apiBase = config.apiBase;This works in Node (14.8+) and every current browser. It is genuinely useful for module initialisation: loading config, opening a database connection, or dynamically importing a module based on a runtime condition. Two caveats. It only works in ES modules, not CommonJS (require), and a slow top-level await delays every module that imports yours, so keep it for real initialisation, not arbitrary work.
A note for Node specifically: fetch is a global since Node 18, so the examples above run server-side with no node-fetch install. It landed experimentally in 18 and was marked stable in Node 21. If you are on older Node, you still need the package, but for anything current, fetch just works. For the request and response model in depth, see the practical fetch() guide, and for cancelling or timing out a request, adding a timeout to fetch with AbortController.
How async functions work internally
An async function is a generator with a runner bolted on. Before async/await (ES2017), people drove asynchronous flows with generators plus a runner: the generator yields a promise, the runner waits for it, then resumes the generator with the resolved value. Kyle Simpson and others taught this pattern heavily around 2014, and libraries like co packaged the runner. Reduced to its essentials:
// A runner: feed it a generator that yields promises, get back a promise.
function teRunAsync(genFn) {
return new Promise((resolve, reject) => {
const gen = genFn();
function step(method, arg) {
let result;
try {
result = gen[method](arg); // .next(value) or .throw(error)
} catch (err) {
return reject(err);
}
if (result.done) return resolve(result.value);
// Wait for the yielded promise, then resume the generator.
Promise.resolve(result.value).then(
(value) => step("next", value),
(error) => step("throw", error)
);
}
step("next");
});
}
// Usage: yield where you would later write await.
teRunAsync(function* () {
const user = yield fetch("/api/me").then((r) => r.json());
const posts = yield fetch(`/api/posts?u=${user.id}`).then((r) => r.json());
return posts.length;
}).then((count) => console.log(count));Swap function* for async function and yield for await and you have the modern version. They are the same machine: await is yield, async supplies the runner, and the engine does it natively (it does not literally instantiate a generator object, but the suspend and resume model is the same). That is why an async function always returns a promise (the runner produces one) and why await hands control back to the event loop instead of blocking.
Async generators and for await...of
The place that heritage becomes a feature is the async generator (async function*), which can both await and yield. You consume it with for await...of. It has been in the language since ES2018, in Node.js 10 and every evergreen browser since early 2020. It fits anything that arrives in pieces, like a paginated API:
async function* teFetchPages(url) {
let next = url;
while (next) {
const res = await fetch(next);
const page = await res.json();
for (const item of page.items) {
yield item; // hand one record to the consumer
}
next = page.nextPage; // null when there are no more pages
}
}
for await (const item of teFetchPages("/api/items?page=1")) {
console.log(item.id);
}The consumer never sees the pagination, and gets back-pressure for free: the next page is not requested until it asks for the next item. A streamed fetch body works the same way, since response.body is itself an async iterable; see streaming a fetch response with ReadableStream.
The AsyncFunction constructor
AsyncFunction is not a global. You reach it through the prototype of any async function, and it builds an async function from a string, the async sibling of new Function(...):
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const fn = new AsyncFunction(
"ms",
"await new Promise((r) => setTimeout(r, ms)); return 'done';"
);
await fn(50); // "done"The honest use case is narrow dynamic codegen (a rules engine, a sandboxed evaluator you own). It is slower, does not close over local scope, and feeding it untrusted strings is eval by another name.
Detecting an async function
fn?.constructor?.name === "AsyncFunction" works in a plain modern engine, but it breaks once Babel, esbuild, or TypeScript's older targets compile async/await down to generators or state machines. More to the point, you rarely need the answer: an async function and a function that returns a promise are interchangeable from the caller's side, so just await handler(input) and let the language normalize it.
Common promise mistakes
Most promise bugs are the same handful of mistakes, and they bite hardest when the code looks like it works. Two are covered above: wrapping a promise in new Promise and forEach with an async callback (see the await-in-a-loop section). These are the rest.
Unhandled rejections crash Node
Since Node 15 (October 2020), an unhandled rejection terminates the process with a non-zero exit, like an uncaught throw. The old UnhandledPromiseRejectionWarning behaviour only comes back if you opt in with --unhandled-rejections=warn. Browsers do not crash the page, but they fire a window.onunhandledrejection event and log to the console. Handle the rejection at the call site with try/catch or .catch. process.on('unhandledRejection', ...) is a last-resort logger for telemetry on the way down, not a way to keep a process alive whose state you no longer trust.
Missing return in a .then callback
The chain links on what each callback returns. Drop the return and the next .then receives undefined, and a rejection inside the un-returned branch escapes your trailing .catch:
// Bug: the inner fetch is fired but not returned
function te_loadProfile(id) {
return fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((user) => {
fetch(`/api/orders/${user.id}`); // missing return
})
.then((orders) => orders.json()); // orders is undefined
}
// Fix: return the promise so the chain waits and errors propagate
function te_loadProfile(id) {
return fetch(`/api/users/${id}`)
.then((res) => res.json())
.then((user) => fetch(`/api/orders/${user.id}`))
.then((orders) => orders.json());
}This is one of the strongest arguments for await: there is no callback to forget a return in.
Floating promises
A floating promise is one you start and neither await nor .catch. If it rejects you get an unhandled rejection (a crash on Node), and even when it resolves, the rest of the function does not wait for it. If the result matters, await it. If it is genuinely fire-and-forget, attach a .catch so a failure is logged instead of fatal:
async function te_handler(req, res) {
await te_writeAuditLog(req).catch((err) =>
console.error("audit log failed:", err)
);
res.send("ok");
}The no-floating-promises rule from typescript-eslint catches this class of bug and is worth turning on.
Mixing await and .then
return te_render(post).then((html) => te_upload(html)) inside an async function compiles, but it scatters error handling between try/catch and .catch. Commit to await: const html = await te_render(post); return te_upload(html);. Appending a deliberate .catch or .finally to one awaited expression is fine; interleaving the two styles across a function is what to avoid.
Redundant Promise.resolve
async function te_config() { return Promise.resolve({ retries: 3 }); } adds nothing: an async function already wraps whatever you return, and a throw becomes a rejection. Return { retries: 3 } directly.
Expecting .finally to handle the error
fetch(url).finally(() => hideSpinner()) still rejects if fetch rejects; .finally did cleanup, not error handling. The await form makes the split explicit:
async function te_fetchWithSpinner(url) {
showSpinner();
try {
const res = await fetch(url);
return res.json();
} finally {
hideSpinner(); // runs on success and on throw
}
}The one way .finally does change the outcome is when its own callback throws or returns a rejecting promise, which replaces the original result. Keep .finally callbacks side-effect-only.
FAQ
They do the same thing; async/await is syntax built on promises. In 2026 await is the default style because it reads top-to-bottom and lets you use ordinary try/catch for errors. Plain .then() still shines for short one-liners and for fan-out with combinators like Promise.all. They mix freely, though mixing both in the same function tends to get confusing.
Each await inside a for loop waits for the previous iteration. If the iterations are independent, start them all and await together with await Promise.all(items.map(fn)); if there are many, cap them with a concurrency pool. The await-in-a-loop section has the timing comparison.
Only in an ES module (.mjs, or .js with "type": "module"). A CommonJS file that uses require throws a syntax error on it. Details in top-level await.
Promise.all rejects on the first failure and drops the other results; Promise.allSettled never rejects and gives you every outcome. The comparison table covers race and any as well.
It depends on what you are hitting. For a rate-limited API, match the documented limit (often 5 to 20 requests in flight). For local disk or CPU work, the core count is a reasonable starting point. Start conservative, watch for 429s and errors, and raise it only if the downstream tolerates it. Unbounded is almost never right against a network resource.
No, because a blocking sleep would freeze the page or the Node event loop. Use const sleep = ms => new Promise(r => setTimeout(r, ms)) and await it, or in Node, setTimeout from node:timers/promises. See sleep, wait, and poll.
No. A correct debounce is about ten lines of standard JavaScript using setTimeout, clearTimeout, and rest params, and a throttle is about a dozen. Reach for a library only if you already use one and want its edge-case options.
See also
- The practical fetch() guide: the request and response model, why
fetchdoes not reject on 4xx, and theresponse.okcheck. - Add a timeout to fetch with AbortController: cancelling and timing out a request with
AbortSignal.timeout(), in the browser and in Node. - Stream a fetch() response with ReadableStream: consuming
response.bodyas an async iterable, the production payoff offor await...of.
Sources
Authoritative references this article was fact-checked against.
- Global objects: AbortSignal.timeout() and AbortSignal.any() (Node.js docs)nodejs.org
- Promise, MDN Web Docsdeveloper.mozilla.org
- Using promises, MDN Web Docsdeveloper.mozilla.org
- async function, MDN Web Docsdeveloper.mozilla.org
- await, MDN Web Docsdeveloper.mozilla.org
- Promise Objects, ECMAScript Language Specification (TC39)tc39.es
- Array.prototype.forEach(): MDN Web Docsdeveloper.mozilla.org
- process 'unhandledRejection' event, Node.js docsnodejs.org
- --unhandled-rejections CLI flag, Node.js docsnodejs.org
- async function* (async generators): MDNdeveloper.mozilla.org
- AsyncFunction, MDNdeveloper.mozilla.org
- Async Function Objects, ECMAScript spec (TC39)tc39.es
- Promise.all(): MDNdeveloper.mozilla.org
- p-limit README (official)github.com
- p-map README (official)github.com
- AbortSignal, MDNdeveloper.mozilla.org
- Promise.allSettled(): MDNdeveloper.mozilla.org
- Promise.race(): MDNdeveloper.mozilla.org
- Promise.any(): MDNdeveloper.mozilla.org
- AggregateError, MDNdeveloper.mozilla.org
- Window: setTimeout() method (MDN)developer.mozilla.org
- Node.js timers/promises (official docs)nodejs.org
- Performance: now() method (MDN)developer.mozilla.org
- Heavy throttling of chained JS timers beginning in Chrome 88 (Chrome for Developers)developer.chrome.com
- setTimeout (MDN Web Docs)developer.mozilla.org
- AbortController (MDN Web Docs)developer.mozilla.org
- Window requestAnimationFrame() (MDN Web Docs)developer.mozilla.org
- useDeferredValue (React documentation)react.dev





