JavaScript Tutorial: Promises
Understand Promises deeply — creating them, chaining .then(), handling errors with .catch(), and combining with Promise.all and Promise.race.
Asynchronous programming, part one
JavaScript runs on a single thread — it can't wait for a network request without freezing the entire page. Promises are how it handles work that takes time.
Before Promises existed, JavaScript used callback functions — leading to the infamous 'callback hell'. Promises brought sanity. Then `async/await` (Chapter 18) brought even more — but it's built entirely on Promises, so you need to understand them first.
What you'll learn in this JavaScript promises tutorial
This interactive JavaScript tutorial has 9 hands-on exercises. Estimated time: 22 minutes.
- What is a Promise? — A Promise represents a value that doesn't exist yet — but will in the future (or won't, if something goes wrong).
- Simulating async work — In the real world, Promises wrap async operations (network calls, file reads). We'll simulate them with `setTimeout`.
- .catch — handle rejection — `.catch(fn)` handles a rejected Promise. Always add it — unhandled rejections crash Node.js.
- .then chaining — Each `.then()` returns a new Promise — so you can chain them.
- .finally — always runs — `.finally()` runs whether the Promise fulfilled or rejected — just like `finally` in try/catch.
- Promise.all — run in parallel — `Promise.all([p1, p2, p3])` runs all Promises in parallel and waits for ALL to complete.
- Promise.allSettled — get all results — `Promise.allSettled` waits for all Promises and gives you all results — even the failed ones.
- Promise.race — first one wins — `Promise.race([p1, p2, p3])` resolves or rejects as soon as the FIRST Promise settles.
- Build a retry mechanism — Final challenge — no starter code.
JavaScript Promises concepts covered
- Asynchronous programming, part one