Async JavaScript

async/await

async functions always return Promises, and await pauses the current async function until a Promise settles while allowing the event loop to continue running other work.
  • async wraps return values in Promises
  • await unwraps fulfillment or throws rejection
  • Await pauses the function, not the whole runtime
  • Sequential awaits serialize work
  • Top-level await changes module loading
Sequential vs concurrent awaits
PatternBehaviorUse when
await a(); await b();b starts after a finishesb depends on a
const pa = a(); const pb = b(); await Promise.all([pa, pb])a and b run concurrentlyindependent work
for await (...) Consumes async sequenceStream/incremental data
Avoid accidental serialization
// Slower if independent:
const user = await loadUser(id)
const projects = await loadProjects(id)

// Faster if independent:
const [user2, projects2] = await Promise.all([
  loadUser(id),
  loadProjects(id),
])
The best async code says which operations depend on which.
Sources
  • MDN JavaScript Guide and ReferenceAsync functions
  • The Modern JavaScript TutorialAsync/await
  • Node.js Documentation and Learn Node.jsAsynchronous work