**.then()** is how you consume a resolved Promise value. Each `.then()` returns a **new Promise**, enabling **chaining**. The return value of a `.then()` callback becomes the resolved value of the next Promise in the chain. Throwing inside `.then()` rejects the next Promise.
1Understanding .then() Method
.then() is how you consume a resolved Promise value. Each .then() returns a new Promise, enabling chaining. The return value of a .then() callback becomes the resolved value of the next Promise in the chain. Throwing inside .then() rejects the next Promise.
Return values from .then() callbacks are automatically wrapped in resolved Promises. Return a Promise to chain async operations.
fetch('/api/user/1')
.then(response => {
if (!response.ok) throw new Error('Not found');
return response.json(); // returns a Promise
})
.then(user => {
return fetch(`/api/posts?userId=${user.id}`);
})
.then(res => res.json())
.then(posts => console.log(posts.length))
.catch(err => console.error(err));2Practical Example
Here is a real-world application of .then() Method showing how it is used in production JavaScript code.
// then with both callbacks
const p = Math.random() > 0.5
? Promise.resolve('success')
: Promise.reject(new Error('failure'));
p.then(
value => console.log('Resolved:', value),
error => console.log('Rejected:', error.message)
);3Best Practices
Follow these guidelines when working with .then() Method:
1. Always return values in .then() callbacks for proper chaining
2. Don't forget to return Promises inside .then()
3. Use .catch() at the end of chains to handle any rejection
Tip: Return values from .then() callbacks are automatically wrapped in resolved Promises. Return a Promise to chain async operations.
fetch('/api/user/1')
.then(response => {
if (!response.ok) throw new Error('Not found');
return response.json(); // returns a Promise
})
.then(user => {
return fetch(`/api/posts?userId=${user.id}`);
})
.then(res => res.json())
.then(posts => console.log(posts.length))
.catch(err => console.error(err));