Catching success with then
Learn to capture the successful result with then.
Catching the result with then
To receive the result when a promise fulfils, you call the then method. then takes a function and passes the resolved value into it.
const order = new Promise(resolve => resolve('shipped'));
order.then(status => {
console.log(status);
});then itself returns a new promise, which lets you chain calls. Unlike callbacks, it runs automatically when the result is ready.
Chaining
Because each then returns a new promise, you can process results in sequence. The value a then returns is passed to the next then.
fetchOrder()
.then(order => order.id)
.then(id => console.log(id));This chain replaces nested callbacks and keeps the code readable top to bottom. Each step passes data to the next.
Exercise Log the name with two then calls
A function called loadUser returns a promise that resolves to a user object. Call loadUser; in the first then return the user's name property; in the second then log that name with console.log.
Show example solution
loadUser()
.then(user => user.name)
.then(name => console.log(name));
Test yourself
-
What does the then method return?
- The resolved value
- undefined
- A new promise
- The original promise
Show answer
A new promise — Correct! then always returns a new promise.
-
The second link of the chain
fetchOrder() .then(order => order.id) .____(id => console.log(id));Show answer
fetchOrder() .then(order => order.id) .then(id => console.log(id)); -
Match then concepts
- then
- Catches the success
- return value
- Passed to next then
- chaining
- Orders then calls