{ ILoveJS }

JavaScript Promises & Async Cheatsheet

javascript

Promises, async/await, and async patterns reference.

7 sections · 44 items

Promise Basics

Promise Constructor
new Promise((resolve, reject) => { ... })

Creates a new Promise with executor function that receives resolve and reject callbacks

typescript
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});
Promise.resolve()
Promise.resolve(value)

Returns a Promise that resolves with the given value immediately

typescript
Promise.resolve(42).then(x => console.log(x)); // 42
Promise.reject()
Promise.reject(reason)

Returns a Promise that rejects with the given reason immediately

typescript
Promise.reject(new Error('fail')).catch(e => console.log(e.message));
then()
promise.then(onFulfilled, onRejected)

Attaches callbacks for fulfillment and rejection, returns a new Promise

typescript
fetch(url).then(res => res.json()).then(data => console.log(data));
catch()
promise.catch(onRejected)

Attaches a rejection handler callback, returns a new Promise

typescript
fetch(url).then(res => res.json()).catch(err => console.error(err));
finally()
promise.finally(onFinally)

Attaches a handler called when promise settles regardless of outcome

typescript
fetch(url)
  .then(res => res.json())
  .finally(() => hideSpinner());

Promise Static Methods

Promise.all()
Promise.all(iterable)

Resolves when all promises resolve or rejects when any promise rejects

typescript
const [a, b] = await Promise.all([fetch(url1), fetch(url2)]);
Promise.allSettled()
Promise.allSettled(iterable)

Resolves when all promises settle with array of result objects containing status and value/reason

typescript
const results = await Promise.allSettled([p1, p2]);
results.forEach(r => console.log(r.status));
Promise.race()
Promise.race(iterable)

Settles as soon as any promise settles with that result

typescript
const first = await Promise.race([fetch(url), timeout(5000)]);
Promise.any()
Promise.any(iterable)

Resolves when any promise fulfills or rejects with AggregateError if all reject

typescript
const fastest = await Promise.any([fetch(mirror1), fetch(mirror2)]);
Promise.withResolvers()
const { promise, resolve, reject } = Promise.withResolvers()

Returns an object with a new promise and its resolve/reject functions

typescript
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve('done'), 1000);

Async/Await Syntax

Async Function Declaration
async function name(params) { ... }

Declares an async function that implicitly returns a Promise

typescript
async function fetchUser(id) {
  const res = await fetch(`/users/${id}`);
  return res.json();
}
Async Arrow Function
const fn = async (params) => { ... }

Arrow function syntax for async functions

typescript
const getUser = async (id) => {
  return await db.users.find(id);
};
Async Method
{ async methodName() { ... } }

Async method syntax in objects and classes

typescript
class API {
  async fetchData() { return await fetch(this.url); }
}
Await Expression
const result = await promise

Pauses async function execution until promise settles and returns its value

typescript
const response = await fetch(url);
const data = await response.json();
Top-Level Await
const data = await fetch(url); // in ES modules

Use await at module top level without wrapping in async function

typescript
// config.js (ES module)
export const config = await fetch('/config.json').then(r => r.json());
Await with Non-Promise
const x = await nonPromiseValue

Await wraps non-promise values in Promise.resolve automatically

typescript
const x = await 42; // x === 42

Error Handling

Try/Catch with Await
try { await promise } catch (err) { ... }

Catches rejected promises in async functions using standard try/catch

typescript
try {
  const data = await fetch(url);
} catch (err) {
  console.error('Failed:', err);
}
Catch Method Chain
asyncFn().catch(err => handleError(err))

Handle errors when calling async function without await

typescript
fetchUser(1).catch(err => showErrorMessage(err.message));
Try/Catch/Finally
try { ... } catch (e) { ... } finally { ... }

Finally block runs regardless of success or failure

typescript
try {
  await saveData();
} catch (e) {
  logError(e);
} finally {
  cleanup();
}
Error in Promise Chain
promise.then(...).then(...).catch(err => ...)

Single catch handles errors from any point in the chain

typescript
fetch(url)
  .then(r => r.json())
  .then(processData)
  .catch(handleAnyError);
Rethrowing Errors
catch (err) { throw err; }

Rethrow error after handling to propagate to outer handlers

typescript
try {
  await riskyOp();
} catch (err) {
  logError(err);
  throw err;
}
Custom Error Class
class CustomError extends Error { ... }

Create custom error types for better error handling

typescript
class NetworkError extends Error {
  constructor(msg) { super(msg); this.name = 'NetworkError'; }
}

AbortController & Cancellation

Create AbortController
const controller = new AbortController()

Creates a controller object that can abort async operations

typescript
const controller = new AbortController();
const signal = controller.signal;
AbortController.signal
controller.signal

Returns the AbortSignal object to pass to abortable operations

typescript
fetch(url, { signal: controller.signal });
AbortController.abort()
controller.abort(reason?)

Aborts the operation with optional reason

typescript
setTimeout(() => controller.abort('timeout'), 5000);
Fetch with AbortSignal
fetch(url, { signal })

Pass signal to fetch to make request cancellable

typescript
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
ctrl.abort();
AbortSignal.timeout()
AbortSignal.timeout(ms)

Returns a signal that auto-aborts after specified milliseconds

typescript
await fetch(url, { signal: AbortSignal.timeout(5000) });
AbortSignal.any()
AbortSignal.any([signal1, signal2])

Returns a signal that aborts when any of the given signals abort

typescript
const signal = AbortSignal.any([ctrl.signal, AbortSignal.timeout(3000)]);
Check if Aborted
signal.aborted

Boolean indicating whether the signal has been aborted

typescript
if (signal.aborted) {
  throw new Error('Operation cancelled');
}
Listen for Abort
signal.addEventListener('abort', handler)

Register callback to run when abort is triggered

typescript
signal.addEventListener('abort', () => {
  console.log('Aborted:', signal.reason);
});

Async Iteration

for-await-of Loop
for await (const item of asyncIterable) { ... }

Iterates over async iterables awaiting each value

typescript
for await (const chunk of readableStream) {
  process(chunk);
}
Async Generator Function
async function* name() { yield await ...; }

Generator that can await promises and yield values asynchronously

typescript
async function* fetchPages(urls) {
  for (const url of urls) yield await fetch(url);
}
Async Generator Method
{ async *methodName() { ... } }

Async generator method syntax in objects and classes

typescript
const obj = {
  async *getData() { yield await fetchItem(); }
};
Symbol.asyncIterator
[Symbol.asyncIterator]() { return asyncIterator; }

Define custom async iterable protocol on objects

typescript
const iterable = {
  async *[Symbol.asyncIterator]() { yield 1; yield 2; }
};
Iterate ReadableStream
for await (const chunk of response.body) { ... }

ReadableStreams are async iterables in modern environments

typescript
const res = await fetch(url);
for await (const chunk of res.body) {
  console.log(chunk);
}

Common Patterns

Sequential Execution
for (const item of items) { await process(item); }

Process async operations one at a time in sequence

typescript
for (const url of urls) {
  await fetch(url);
}
Parallel Execution
await Promise.all(items.map(fn))

Execute all async operations concurrently

typescript
const results = await Promise.all(urls.map(url => fetch(url)));
Concurrency Limit
// process N items at a time

Control maximum concurrent operations using batching or pools

typescript
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));
}
Timeout Wrapper
Promise.race([promise, timeout()])

Add timeout to any promise using Promise.race

typescript
const withTimeout = (p, ms) => Promise.race([
  p,
  new Promise((_, rej) => setTimeout(() => rej('timeout'), ms))
]);
Retry Pattern
async function retry(fn, retries) { ... }

Retry failed async operations with configurable attempts

typescript
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; }
}
Debounced Async
let pending; const debounced = async () => { ... }

Debounce async function calls to avoid race conditions

typescript
let pending;
async function search(q) {
  pending?.abort();
  pending = new AbortController();
  return fetch(q, { signal: pending.signal });
}
Promisify Callback
new Promise((resolve, reject) => callbackFn(...))

Convert callback-based function to Promise

typescript
const readFile = (path) => new Promise((res, rej) =>
  fs.readFile(path, (err, data) => err ? rej(err) : res(data))
);
Sleep/Delay
const sleep = ms => new Promise(r => setTimeout(r, ms))

Create a promise that resolves after specified delay

typescript
const sleep = ms => new Promise(r => setTimeout(r, ms));
await sleep(1000);

Related Content