.then()
Registers callbacks for the fulfillment (and optionally rejection) of a promise and returns a new promise chained to the callback's return value. Returning a value fulfills the next promise; throwing or returning a rejected promise rejects it.
promise.then(onFulfilled, onRejected?) Parameters
| Parameter | Purpose |
|---|---|
| onFulfilled(value) | Called with the resolved value |
| onRejected(reason) | Optional; catches rejections in this chain link |
| returns | A NEW promise — enables chaining |
Examples
fetch('/api/user')
.then(r => r.json())
.then(user => console.log(user.name)); Each .then unwraps the returned promise for the next handler.
Promise.resolve(1)
.then(n => n + 1)
.then(n => { throw new Error('nope'); })
.then(n => console.log('skipped'), err => console.error(err.message)); A thrown error skips subsequent fulfillment handlers until an onRejected is found.
// Prefer .catch over the second argument
fetch(url).then(r => r.json()).catch(err => console.error(err)); Two-argument form doesn't catch errors thrown INSIDE onFulfilled — .catch does.
Gotcha
The onRejected argument of .then does NOT catch errors thrown in its own onFulfilled — chain a .catch instead. Forgetting to return the inner promise breaks the chain (the outer .then resolves before the inner work finishes).
Related
← All JS Promise reference · async/await vs promises vs callbacks