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.

Return value

A Promise.

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. Values returned from the onFulfilled or onRejected callback functions will be automatically wrapped in a resolved promise.

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 Edge Firefox Internet Explorer Opera Safari Servo
Basic Support32.0(Yes)29.0No support197.1No support
Feature Android Chrome for Android Edge Mobile Firefox for Android IE Mobile Opera Mobile Safari Mobile
Basic Support4.4.432.0(Yes)29No support(Yes)8.0

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/promise/then