Lessons in this course (16)

9. Promises and async/await

Intermediate★ Must knowLesson 9 of 16
js
// Promise states: pending → fulfilled | rejected (settled once)
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

fetch("/api/orders/1")
  .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
  .then(order => console.log(order))
  .catch(err => console.error(err))
  .finally(() => hideSpinner());

async function loadDashboard(userId) {
  try {
    const [user, orders] = await Promise.all([            // run in parallel
      fetch(`/api/users/${userId}`).then(r => r.json()),
      fetch(`/api/orders?user=${userId}`).then(r => r.json()),
    ]);
    return { user, orders };
  } catch (err) {
    console.error("Dashboard failed", err);
    throw err;
  }
}

// Timeout / cancellation with AbortController
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
const res = await fetch("/api/report", { signal: controller.signal });   // or AbortSignal.timeout(5000)
CombinatorResolves whenRejects when
Promise.allAll fulfil (array of values)First rejection
Promise.allSettledAll settle (status objects)Never
Promise.raceFirst to settle (value)First to settle is a rejection
Promise.anyFirst to fulfilAll reject (AggregateError)

async functions always return a promise; await pauses the function (not the thread) until the promise settles. Sequential awaits in a loop run one by one — use Promise.all for independent work.