Promise.prototype.then()

Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.

Returns
A new promise, fulfilled with the value your function returns, or rejected if the function throws.
On this page

Example

#
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))

wait(200, 120)
  .then((points) => points + 30)
  .then((points) => {
    console.log(`You have ${points} points`)
    return wait(200, points >= 150)
  })
  .then((levelUp) => console.log('New level:', levelUp))
Console
You have 150 points
New level: true

Definition and usage

#

The then() method takes a function that gets called with the promise’s value once it’s fulfilled. The optional second argument is an error-handling function, but it’s more common to use a separate catch() at the end of the chain instead.

then() always returns a new promise. Its value becomes whatever your function returns. A plain value passes straight to the next then(), while a returned promise makes the chain wait for its result. That lets successive steps (fetch, process, display) line up one after another instead of nesting.

The most common mistake is a missing return inside the chain. The next step then gets undefined and doesn’t wait for the asynchronous operation started in the previous step to finish.

Syntax

#
Syntax
promise.then(onFulfilled)
promise.then(onFulfilled, onRejected)

Parameters

#
  • onFulfilled

    function (value)

    The function called with the fulfilled promise’s value. Whatever it returns becomes the value of the new promise.
  • onRejected

    optional function (reason)

    The function called when the promise is rejected. It’s usually more convenient to use catch() instead.

More examples

#
Pitfall: a forgotten return
JavaScript
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))

wait(100, 'Lesson 1')
  .then((lesson) => {
    wait(100, lesson + ' completed')
  })
  .then((result) => console.log(result))
Console
undefined

A function in curly braces without return returns undefined, so the next then() doesn’t wait for the inner promise. Just add return, or remove the braces.

then() always runs asynchronously
JavaScript
Promise.resolve('from the promise').then((value) => console.log(value))
console.log('synchronously')
Console
synchronously
from the promise

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Return a value or a promise at every step of the chain. An arrow function without braces does this automatically.
  • A single catch() at the end of the chain catches an error from any earlier step.
  • With many steps, consider async and await instead. That kind of code reads like ordinary top-to-bottom code.

Related entries

#

Spotted a mistake or missing an example? Write to us.