Chapter 12 Cheatsheet: Promises

This cheatsheet summarizes the mechanics of asynchronous programming and Promises in JavaScript covered in Chapter 12.

Async Fundamentals

Synchronous code blocks the execution thread until finished. Asynchronous code (like timers or HTTP requests) runs in the background, freeing up the main thread to keep the application responsive.

The Promise Object

A Promise represents an async operation that will eventually resolve (succeed) or reject (fail).

const myPromise = new Promise((resolve, reject) => {
  if (success) resolve("Done!");
  else reject("Failed!");
});

Legacy Handling: .then / .catch

You can handle Promises by chaining callbacks.

myPromise
  .then(result => console.log(result))
  .catch(error => console.error(error));

Modern Handling: async / await

The async keyword automatically wraps a function’s return value in a Promise. The await keyword pauses execution until a Promise resolves, returning the raw data.

async function fetchUser() {
  try {
    // Pauses here until network finishes
    const user = await fetch("/api/user"); 
    return user;
  } catch (error) {
    // Handles promise rejections
    console.log("Network failed", error);
  }
}

Rule of thumb: Always prefer async/await with standard try/catch blocks over chaining .then() and .catch().