JavaScript Reference ยท Promises and Async
Promise.prototype.then()
Reference for Promise.prototype.then(): attach fulfillment and rejection handlers, chain promises, understand return values, errors and timing.
The then() method attaches handlers to a promise and returns a new promise. The first handler runs when the promise fulfills, the optional second one when it rejects. Whatever the handler returns becomes the value of the new promise, which is what makes chaining possible.
Handlers never run synchronously. Even if the promise is already settled, the handler is queued as a microtask and runs after the current code finishes.
fetchNumber() .then((n) => n * 2) .then((double) => console.log(double));
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
promise.then(onFulfilled) promise.then(onFulfilled, onRejected)
| Name | Description |
|---|---|
onFulfilled |
Optional. Called with the fulfillment value. If it is not a function, the value passes through unchanged. |
onRejected |
Optional. Called with the rejection reason. If it is not a function, the rejection passes through. |
Return value: a new promise. It fulfills with the handler's return value (waiting for it if it is a promise or thenable), and rejects if the handler throws.
Exceptions: then() itself does not throw for bad arguments; errors inside handlers become rejections of the returned promise.
Usage notes
- Return inside handlers. Forgetting
returnis the most common bug: the next step then receivesundefinedand does not wait for your inner promise. - A rejection handler recovers. If
onRejectedreturns normally, the chain continues as fulfilled with that value. - Errors skip ahead. A rejection travels down the chain, skipping fulfillment handlers, until a rejection handler or
catch()meets it. - The two-argument form has a blind spot.
onRejecteddoes not handle errors thrown byonFulfilledin the same call. A following.catch()does. - Branching. Calling
then()twice on the same promise creates two independent branches, both running when it settles. - Thenables. Any object with a
then()method can be returned from a handler and will be followed. - Prefer
awaitfor long sequences;then()remains useful for small transformations and in code that cannot beasync.
Browser support
Supported in every current browser and Node.js.
Related
- Promise, catch(), finally()
- async and await
- Lesson: Promises