Glossary / async and await

async and await

async functions let code express Promise-based control flow with syntax resembling synchronous code. Calling an async function always returns a Promise: a returned value fulfills it, and a thrown exception rejects it. await suspends that function’s continuation until the awaited value settles; it does not block the JavaScript thread or create a new thread.

Sequencing and concurrency

async function loadView(id) {
  const response = await fetch(`/items/${id}`);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

Awaiting a non-Promise behaves like awaiting an already-fulfilled value, with continuation still occurring asynchronously. A rejected Promise is thrown at the await expression and can be caught with try/catch. An async function’s try/finally is useful for cleanup across suspension, but cancellation must still reach the underlying operation.

Two awaits in sequence serialize the operations. For independent work, start both and await Promise.all; avoid accidental unbounded fan-out. forEach(async ...) does not wait for callbacks—use for...of for serial iteration or Promise.all for bounded parallelism. Return Promises from callbacks and callers so errors remain connected to an observed chain.

Interview questions

  1. Does async/await block the thread? No; await suspends the function continuation and returns control to the host.
  2. What does an async function always return? A Promise.
  3. How does await handle rejection? It throws at the await point.
  4. How run independent requests concurrently? Start them before awaiting, commonly with Promise.all.
  5. Why is forEach(async ...) often wrong? forEach ignores callback Promises and does not await completion.

References