Lexicon
⌘K
Explore
GuidesNotes
QuestionsWriteMy LibraryBooks
Sign in

Lexicon

a personal knowledge base

← Back to note

Version history

No earlier versions yet — history builds up each time this note is edited.

Current version1 of 1

JavaScript

JavaScript async and await

async/await is syntax sugar over Promises that lets asynchronous code read top to bottom like normal code. Under the hood it is still Promises.

The basics

An async function always returns a Promise. await pauses inside that function until the awaited Promise settles.

async function getUser(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

Error handling

Wrap awaits in try/catch instead of .catch() chains.

try {
  const user = await getUser(42);
  console.log(user.name);
} catch (err) {
  console.error('failed to load user', err);
}

Do not serialize by accident

Awaiting inside a loop runs requests one after another. If they are independent, fire them together with Promise.all.

// Slow: each await waits for the previous one
for (const id of ids) {
  results.push(await getUser(id));
}

// Fast: all requests in flight at once
const results = await Promise.all(ids.map(getUser));

Parallel vs settled

  • Promise.all rejects as soon as any one rejects
  • Promise.allSettled waits for every promise and reports each result, good when partial failure is acceptable

Common gotcha

forEach does not await. Use a for...of loop or map with Promise.all.

// This does NOT wait, the callback is async but forEach ignores the promise
items.forEach(async (item) => { await save(item); });