Promise.prototype.then()

The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise.

Syntax

p.then(onFulfilled, onRejected);

p.then(function(value) {
   // fulfillment
  }, function(reason) {
  // rejection
});

Parameters

onFulfilled
A Function called when the Promise is fulfilled. This function has one argument, the fulfillment value.
onRejected
A Function called when the Promise is rejected. This function has one argument, the rejection reason.

Description

As the then and Promise.prototype.catch() methods return promises, they can be chained — an operation called composition.

Examples

Using the then method

var p1 = new Promise(function(resolve, reject) {
  resolve("Success!");
  // or
  // reject ("Error!");
});

p1.then(function(value) {
  console.log(value); // Success!
}, function(reason) {
  console.log(reason); // Error!
});

Chaining

Because the then method returns a Promise, you can easily chain then calls.

var p2 = new Promise(function(resolve, reject) {
  resolve(1);
});

p2.then(function(value) {
  console.log(value); // 1
  return value + 1;
}).then(function(value) {
  console.log(value); // 2
});

p2.then(function(value) {
  console.log(value); // 1
});

You can also use chaining to implement one function with a Promise-based API on top of another such function.

function fetch_current_data() {
  // The fetch() API returns a Promise.  This function
  // exposes a similar API, except the fulfillment
  // value of this function's Promise has had more
  // work done on it.
  return fetch("current-data.json").then((response) => {
    if (response.headers.get("content-type") != "application/json") {
      throw new TypeError();
    }
    var j = response.json();
    // maybe do something with j
    return j; // fulfillment value given to user of
              // fetch_current_data().then()
  });
}

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise.prototype.then' in that specification.
Standard Initial definition in an ECMA standard.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Promise.prototype.then' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 32 29.0 (29.0) No support 19 7.1
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support 29.0 (29.0) No support No support 8 32

See also

Document Tags and Contributors

 Contributors to this page: SphinxKnight, grabber24, Sheppy, fscholz, DBaron, DenisIzmaylov, realityking
 Last updated by: SphinxKnight,