{{JSRef}} {{harmony}}
The then()
method returns a Promise
. It takes two arguments, both are 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 {{jsxref("Function")}} called when the
Promise
is fulfilled. This function has one argument, the fulfillmentvalue
. - onRejected
- A {{jsxref("Function")}} called when the
Promise
is rejected. This function has one argument, the rejectionreason
.
Description
As the then
and {{jsxref("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 |
---|---|---|
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}} | {{Spec2('ES6')}} | Initial definition in an ECMA standard. |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 32 | {{CompatGeckoDesktop(29.0)}} [1] | {{CompatNo}} | 19 | 7.1 |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatGeckoMobile(29.0)}} [1] | {{CompatNo}} | {{CompatNo}} | 8 | 32 |
[1] Gecko 24 has an experimental implementation of Promise
, under the initial name of Future
. It got renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled
. Bug 918806 enabled Promises by default in Gecko 29.
See also
- {{jsxref("Promise")}}
- {{jsxref("Promise.prototype.catch()")}}