JavaScript Async and Promises Cheat Sheet

Promises, async/await, fetch, timers, generators, async iterables, and event loop patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Promises
Create resolved promise
const p = Promise.resolve({ ok: true });
Create rejected promise
const p = Promise.reject(new Error("Boom"));
then / catch / finally
fetchData()
  .then((data) => transform(data))
  .catch((err) => console.error(err))
  .finally(() => console.log("done"));
Promise.all
const [user, posts] = await Promise.all([getUser(), getPosts()]);
Promise.allSettled
const results = await Promise.allSettled(tasks);
Promise.race
const winner = await Promise.race([fast(), slow()]);
Promise.any
const firstSuccess = await Promise.any(providers);
## Async / Await
Async function
async function loadUser(id) {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
}
Await with try/catch
try {
  const data = await loadUser(1);
  console.log(data);
} catch (err) {
  console.error(err);
}
Sequential await in loop
for (const url of urls) {
  const res = await fetch(url);
  console.log(await res.text());
}
Concurrent await with map
const html = await Promise.all(urls.map(async (url) => {
  const res = await fetch(url);
  return res.text();
}));
Async IIFE
await (async () => {
  const config = await loadConfig();
  console.log(config);
})();
## Fetch API
fetch GET JSON
const res = await fetch("/api/items");
const data = await res.json();
fetch POST JSON
const res = await fetch("/api/items", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload),
});
Check response.ok
if (!res.ok) {
  throw new Error(`HTTP ${res.status}`);
}
Set custom headers
await fetch(url, {
  headers: { Authorization: `Bearer ${token}` },
});
Abort fetch with AbortController
const controller = new AbortController();
setTimeout(() => controller.abort(), 3000);
await fetch(url, { signal: controller.signal });
Timeout with Promise.race
await Promise.race([
  fetch(url),
  new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 3000)),
]);
Send FormData
const form = new FormData();
form.append("file", file);
await fetch("/upload", { method: "POST", body: form });
Simple retry helper
async function withRetry(fn, retries = 3) {
  let lastError;
  for (let i = 0; i < retries; i++) {
    try { return await fn(); } catch (err) { lastError = err; }
  }
  throw lastError;
}
## Timers and Event Loop
setTimeout
const timeoutId = setTimeout(() => {
  console.log("Later");
}, 1000);
clearTimeout
clearTimeout(timeoutId);
setInterval
const intervalId = setInterval(tick, 1000);
clearInterval
clearInterval(intervalId);
queueMicrotask
queueMicrotask(() => {
  console.log("Runs before next macrotask");
});
Debounce helper
function debounce(fn, wait = 250) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}
Throttle helper
function throttle(fn, wait = 250) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn(...args);
    }
  };
}
## Iterables, Generators, and Async Iteration
Basic generator
function* ids() {
  yield 1;
  yield 2;
  yield 3;
}
Consume generator
const gen = ids();
gen.next(); // { value: 1, done: false }
Delegate with yield*
function* combined() {
  yield* [1, 2];
  yield* [3, 4];
}
Custom iterable object
const range = {
  from: 1,
  to: 3,
  *[Symbol.iterator]() {
    for (let i = this.from; i <= this.to; i++) yield i;
  },
};
Async generator
async function* pages() {
  let page = 1;
  while (page <= 3) {
    yield await fetch(`/api/page/${page++}`).then((r) => r.json());
  }
}
for await...of
for await (const page of pages()) {
  console.log(page);
}