The .then() Method
You'll learn how to register a callback that runs when a Promise resolves and receives the resolved value.
What is .then()?
The .then() method is how you "listen" for a Promise to settle successfully. When you call .then() on a Promise, you pass it a callback function. That callback will execute once the Promise resolves, and it automatically receives the resolved value as its argument.
Think of it like ordering food delivery: creating the Promise is like placing your order, and .then() is like saying "when my food arrives, here's what I'll do with it." The delivery person (the Promise) hands you the food (the resolved value), and your callback function decides what to do next.
Basic Syntax
const promise = new Promise((resolve, reject) => {
resolve('Success!');
});
promise.then((value) => {
console.log(value); // 'Success!'
});
The callback you pass to .then() receives whatever value was passed to resolve(). If the Promise was already resolved before you attached .then(), the callback still runs—it gets added to the microtask queue.
Multiple .then() Calls
You can attach multiple .then() handlers to the same Promise:
const promise = new Promise((resolve) => {
resolve(42);
});
promise.then((num) => console.log('First:', num));
promise.then((num) => console.log('Second:', num));
// Both run when the Promise resolves
Each handler receives the same resolved value independently.
Key Takeaway: The .then() method registers a callback that executes when a Promise resolves, automatically receiving the resolved value as its parameter.