Creating & Consuming
Promises
Master asynchronous JavaScript by learning to create Promises with constructors and consume them using .then() and .catch() chains.
What is a Promise?
A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and the resulting value. Think of it like an IOU: the code promises to give you a result later.
The Promise Lifecycle
Why Do We Need Promises?
Before Promises, JavaScript developers used callbacks for async work. Nesting callbacks inside callbacks created "callback hell": deeply indented, hard-to-read, and error-prone code.
The Promise Constructor
You create a new Promise using the Promise constructor. It takes a single function called the executor, which receives two callbacks: resolve and reject.
Consuming: .then() and .catch()
Once a Promise exists, you consume it by attaching handlers. .then() handles fulfilled values; .catch() handles rejections.
Callbacks vs Promises
| Callbacks | Promises | |
|---|---|---|
| Error handling | Manual per callback | Centralized .catch() |
| Readability | Deeply nested (pyramid) | Flat .then() chains |
| Composability | Difficult to combine | Promise.all(), .race() |
| Return values | Cannot return from async | Chainable return values |
| Guarantees | Callback may fire 0, 1, or 2+ times | Settles exactly once |
Chaining .then() Calls
Because .then() returns a new Promise, you can chain multiple .then() calls. Each step transforms the data and passes it along.
How the Chain Flows
How to Apply Promises
Example 1: Coin Flip Promise
Example 2: Delayed Timer
Example 3: Real-World Fetch
.finally() and Two-Argument .then()
Common Mistakes
Promise Method Cheatsheet
| Method | When it runs | Receives |
|---|---|---|
| .then(fn) | On fulfillment | The resolved value |
| .catch(fn) | On rejection | The rejection reason |
| .finally(fn) | On settlement (either) | Nothing (no args) |
| Promise.resolve(v) | Immediately fulfilled | Wraps v in a Promise |
| Promise.reject(r) | Immediately rejected | Wraps r in a Promise |
Question 1 of 5
What are the three possible states of a JavaScript Promise?
Question 2 of 5
What does .then() return?
Question 3 of 5
Consider this code:
new Promise((resolve, reject) => {
resolve("hello");
reject("world");
})
.then((val) => console.log(val))
.catch((err) => console.log(err));
What gets logged to the console?
Question 4 of 5
Consider this code:
Promise.resolve(10)
.then((x) => x * 2)
.then((x) => x + 5)
.then((x) => console.log(x));
What value is logged?
Question 5 of 5
What happens if you forget to add .catch() to a Promise chain that rejects?