JavaScript: .then()
The .then() method continues after a Promise succeeds and passes its result to the next step.
What you will learn
- When
.then()runs after a Promise fulfills - How to return a value for the next
.then() - How to connect failures to
.catch()
Minimal example
fetch("data.json")
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
console.log("Data received:", data);
})
.catch(error => {
console.error("Could not load data:", error);
});Each callback returns a new Promise. Returning response.json() lets the next .then() wait for the parsed data. Throwing an error sends the chain to .catch().
Common mistakes
- Return the next Promise or value when a later step needs it; otherwise it may receive
undefined. - Do not assume
fetch()rejects for HTTP errors; checkresponse.ok. - Use
.catch()to make failures visible and decide how to recover.