Script Valley
JavaScript: The Complete Language
Asynchronous JavaScriptLesson 4.3

async/await: writing asynchronous code that reads synchronously

async function, await keyword, try-catch with async-await, returning from async functions, async functions return promises, parallel execution, error handling patterns

async/await Is Syntactic Sugar Over Promises

async/await lets you write async code that looks and reads like synchronous code. Every async function implicitly returns a Promise. await pauses execution inside the function until the awaited Promise settles — without blocking the thread or the event loop.

Basic Pattern

async function loadUserProfile(id) {
  try {
    const user  = await fetchUser(id);
    const posts = await fetchPosts(user.id);
    return { user, posts };
  } catch (err) {
    console.error("Failed:", err.message);
    throw err; // re-throw so callers know it failed
  }
}

Parallel Execution

Awaiting sequentially when operations are independent wastes time. Use Promise.all to start both at once and await their combined result.

// Sequential — slower: waits for user before starting prefs
const user  = await fetchUser(id);
const prefs = await fetchPrefs(id);

// Parallel — faster: both requests run simultaneously
const [user, prefs] = await Promise.all([
  fetchUser(id),
  fetchPrefs(id)
]);

Key Rules

await only works inside async functions (and at the top level of ES modules). An async function always returns a Promise — even if you return a plain value, it gets wrapped automatically. Use try/catch for error handling, just like synchronous code. Never fire-and-forget an async function without handling its returned Promise or potential rejections.

Up next

Promise.all, Promise.race, Promise.allSettled, Promise.any explained

Sign in to track progress