JavaScript Promises & Async Cheatsheet
javascriptPromises, async/await, and async patterns reference.
Promise Basics
new Promise((resolve, reject) => { ... })Creates a new Promise with executor function that receives resolve and reject callbacks
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 1000);
});Promise.resolve(value)Returns a Promise that resolves with the given value immediately
Promise.resolve(42).then(x => console.log(x)); // 42Promise.reject(reason)Returns a Promise that rejects with the given reason immediately
Promise.reject(new Error('fail')).catch(e => console.log(e.message));promise.then(onFulfilled, onRejected)Attaches callbacks for fulfillment and rejection, returns a new Promise
fetch(url).then(res => res.json()).then(data => console.log(data));promise.catch(onRejected)Attaches a rejection handler callback, returns a new Promise
fetch(url).then(res => res.json()).catch(err => console.error(err));promise.finally(onFinally)Attaches a handler called when promise settles regardless of outcome
fetch(url)
.then(res => res.json())
.finally(() => hideSpinner());Promise Static Methods
Promise.all(iterable)Resolves when all promises resolve or rejects when any promise rejects
const [a, b] = await Promise.all([fetch(url1), fetch(url2)]);Promise.allSettled(iterable)Resolves when all promises settle with array of result objects containing status and value/reason
const results = await Promise.allSettled([p1, p2]);
results.forEach(r => console.log(r.status));Promise.race(iterable)Settles as soon as any promise settles with that result
const first = await Promise.race([fetch(url), timeout(5000)]);Promise.any(iterable)Resolves when any promise fulfills or rejects with AggregateError if all reject
const fastest = await Promise.any([fetch(mirror1), fetch(mirror2)]);const { promise, resolve, reject } = Promise.withResolvers()Returns an object with a new promise and its resolve/reject functions
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve('done'), 1000);Async/Await Syntax
async function name(params) { ... }Declares an async function that implicitly returns a Promise
async function fetchUser(id) {
const res = await fetch(`/users/${id}`);
return res.json();
}const fn = async (params) => { ... }Arrow function syntax for async functions
const getUser = async (id) => {
return await db.users.find(id);
};{ async methodName() { ... } }Async method syntax in objects and classes
class API {
async fetchData() { return await fetch(this.url); }
}const result = await promisePauses async function execution until promise settles and returns its value
const response = await fetch(url);
const data = await response.json();const data = await fetch(url); // in ES modulesUse await at module top level without wrapping in async function
// config.js (ES module)
export const config = await fetch('/config.json').then(r => r.json());const x = await nonPromiseValueAwait wraps non-promise values in Promise.resolve automatically
const x = await 42; // x === 42Error Handling
try { await promise } catch (err) { ... }Catches rejected promises in async functions using standard try/catch
try {
const data = await fetch(url);
} catch (err) {
console.error('Failed:', err);
}asyncFn().catch(err => handleError(err))Handle errors when calling async function without await
fetchUser(1).catch(err => showErrorMessage(err.message));try { ... } catch (e) { ... } finally { ... }Finally block runs regardless of success or failure
try {
await saveData();
} catch (e) {
logError(e);
} finally {
cleanup();
}promise.then(...).then(...).catch(err => ...)Single catch handles errors from any point in the chain
fetch(url)
.then(r => r.json())
.then(processData)
.catch(handleAnyError);catch (err) { throw err; }Rethrow error after handling to propagate to outer handlers
try {
await riskyOp();
} catch (err) {
logError(err);
throw err;
}class CustomError extends Error { ... }Create custom error types for better error handling
class NetworkError extends Error {
constructor(msg) { super(msg); this.name = 'NetworkError'; }
}AbortController & Cancellation
const controller = new AbortController()Creates a controller object that can abort async operations
const controller = new AbortController();
const signal = controller.signal;controller.signalReturns the AbortSignal object to pass to abortable operations
fetch(url, { signal: controller.signal });controller.abort(reason?)Aborts the operation with optional reason
setTimeout(() => controller.abort('timeout'), 5000);fetch(url, { signal })Pass signal to fetch to make request cancellable
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
ctrl.abort();AbortSignal.timeout(ms)Returns a signal that auto-aborts after specified milliseconds
await fetch(url, { signal: AbortSignal.timeout(5000) });AbortSignal.any([signal1, signal2])Returns a signal that aborts when any of the given signals abort
const signal = AbortSignal.any([ctrl.signal, AbortSignal.timeout(3000)]);signal.abortedBoolean indicating whether the signal has been aborted
if (signal.aborted) {
throw new Error('Operation cancelled');
}signal.addEventListener('abort', handler)Register callback to run when abort is triggered
signal.addEventListener('abort', () => {
console.log('Aborted:', signal.reason);
});Async Iteration
for await (const item of asyncIterable) { ... }Iterates over async iterables awaiting each value
for await (const chunk of readableStream) {
process(chunk);
}async function* name() { yield await ...; }Generator that can await promises and yield values asynchronously
async function* fetchPages(urls) {
for (const url of urls) yield await fetch(url);
}{ async *methodName() { ... } }Async generator method syntax in objects and classes
const obj = {
async *getData() { yield await fetchItem(); }
};[Symbol.asyncIterator]() { return asyncIterator; }Define custom async iterable protocol on objects
const iterable = {
async *[Symbol.asyncIterator]() { yield 1; yield 2; }
};for await (const chunk of response.body) { ... }ReadableStreams are async iterables in modern environments
const res = await fetch(url);
for await (const chunk of res.body) {
console.log(chunk);
}Common Patterns
for (const item of items) { await process(item); }Process async operations one at a time in sequence
for (const url of urls) {
await fetch(url);
}await Promise.all(items.map(fn))Execute all async operations concurrently
const results = await Promise.all(urls.map(url => fetch(url)));// process N items at a timeControl maximum concurrent operations using batching or pools
async function batch(items, fn, limit = 3) {
for (let i = 0; i < items.length; i += limit)
await Promise.all(items.slice(i, i + limit).map(fn));
}Promise.race([promise, timeout()])Add timeout to any promise using Promise.race
const withTimeout = (p, ms) => Promise.race([
p,
new Promise((_, rej) => setTimeout(() => rej('timeout'), ms))
]);async function retry(fn, retries) { ... }Retry failed async operations with configurable attempts
async function retry(fn, n = 3) {
for (let i = 0; i < n; i++)
try { return await fn(); } catch (e) { if (i === n-1) throw e; }
}let pending; const debounced = async () => { ... }Debounce async function calls to avoid race conditions
let pending;
async function search(q) {
pending?.abort();
pending = new AbortController();
return fetch(q, { signal: pending.signal });
}new Promise((resolve, reject) => callbackFn(...))Convert callback-based function to Promise
const readFile = (path) => new Promise((res, rej) =>
fs.readFile(path, (err, data) => err ? rej(err) : res(data))
);const sleep = ms => new Promise(r => setTimeout(r, ms))Create a promise that resolves after specified delay
const sleep = ms => new Promise(r => setTimeout(r, ms));
await sleep(1000);