Course outline · 0% complete

0/27 lessons0%

Course overview →

From callbacks to promises

lesson 5-1 · ~11 min · 11/27

Quiz

Warm-up from lesson 4-2: a resolved promise's `.then` callback and a `setTimeout(fn, 0)` are both waiting. Which runs first, and why?

Why promises exist

Async work (network calls, timers, file reads) finishes later. The old pattern was to pass a callback: "when you're done, call this function". Nest a few of those and you get the famous callback pyramid, where step 3 lives four indents deep inside step 2 inside step 1.

A promise flips it around. It is an object that represents a future value, in one of three states:

  • pending: the work is still running
  • fulfilled: done, with a value
  • rejected: failed, with a reason

A promise settles exactly once, and then never changes again. You attach what-happens-next with .then(callback) instead of nesting.

You create one with new Promise(executor). The executor is the name for the function you hand to the constructor: JavaScript calls it immediately and passes it two functions — resolve(value) to fulfill and reject(reason) to fail. Your async work runs inside the executor and reports back through those two calls.

Code exercise · javascript

Run it. `new Promise` takes a function that receives `resolve`. The executor starts a timer, the script keeps going, and `.then` fires when `resolve` is called 50 ms later.

Quiz

When does the executor — the function you pass to `new Promise(...)` — actually run?

pendingfulfilled (value)rejected (reason)resolve(value)reject(reason)
A promise settles once: pending moves to fulfilled or rejected, and the arrows never point back.

Quiz

A promise resolves with "done". A second later you call `resolve("again")` on it. What is the promise's value?

Code exercise · javascript

Your turn. Write `delay(ms, value)` that returns a promise which resolves with `value` after `ms` milliseconds. The test code should print `start` then `done`.