Promise

This article is in need of a technical review.

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.

The Promise interface represents a proxy for a value not necessarily known at its creation time. It allows you to associate handlers to an asynchronous action's eventual success or failure. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

A promise can become either fulfilled with a value, or rejected with a reason. When either of these happens, the associated handlers queued up by a promise's then method are called.

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

Methods

Promise.prototype.then(onFulfilled, onRejected)
Appends fullfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler.
Promise.prototype.catch(onRejected)
Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.

Static methods

Promise.resolve(value)
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.
Promise.reject(reason)
Returns a Promise object that is rejected with the given reason.
Promise.all(iterable)
Returns a promise that resolves when all of the promises in iterable have resolved. The result is passed an array of values from all the promises. If something passed in the iterable array is not a promise, it's converted to one by Promise.cast. If any of the passed in promises rejects, the all Promise immediately rejects with the value of the promise that rejected, discarding all the other promises whether or not they have resolved.
var p = new Promise(function(resolve, reject) { resolve(3); });
Promise.all([true, p]).then(function(values) {
  // values == [ true, 3 ]
});
Promise.race(iterable)
Returns a promise that either resolves when the first promise in the iterable resolves, or rejects when the first promise in the iterable rejects.
var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "one"); });
var p2 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, "two"); });

Promise.race([p1, p2]).then(function(value) {
  // value === "two"
});

var p3 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, "three"); });
var p4 = new Promise(function(resolve, reject) { setTimeout(reject, 500, "four"); });

Promise.race([p3, p4]).then(function(value) {
  // value === "three"               
}, function(reason) {
  // Not called
});

var p5 = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "five"); });
var p6 = new Promise(function(resolve, reject) { setTimeout(reject, 100, "six"); });

Promise.race([p5, p6]).then(function(value) {
  // Not called              
}, function(reason) {
  // reason === "six"
});

Example

This small example shows the mechanism of a Promise. The testPromise() method is called each time the <button> is clicked. It creates a promise that will resolve, using window.setTimeout, to the string 'result' after 1s to 3s (random).

The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

var promiseCount = 0;
function testPromise() {
  var thisPromiseCount = ++promiseCount;

  var log = document.getElementById('log');
  log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Started (<small>Sync code started</small>)<br/>');

  var p1 = new Promise(               /* We make a new promise: we promise the string 'result' (after waiting 3s) */
    function(resolve, reject) {       /* The resolver function is called with the ability to resolve or reject the promise */
      log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise started (<small>Async code started</small>)<br/>');
      window.setTimeout(              /* This only is an example to create asynchronism */
        function() {
          resolve(thisPromiseCount); /* We fulfill the promise ! */
        }, Math.random() * 2000 + 1000);
    });

  p1.then(                            /* We defines what to do when the promise is fulfilled */
    function(val) {                   /* Just log the message and a value */
      log.insertAdjacentHTML('beforeend', val + ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
    });

  log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise made (<small>Sync code terminated</small>)<br/>');
}

This example is executed when clicking the button. You need a browser supporting Promise. By clicking several times the button in a short amount of time, you'll even see the different promise being fulfilled one after the other.

Specification

Specification Status Comment
domenic/promises-unwrapping Draft Initial work is taking place here
ES6 Draft Eventually it will be transferred to the full ES6 draft

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 32 24 (24) as Future
25 (25) as Promise [1]
Not supported 19 Not supported
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support Not supported 24.0 (24) as Future
25.0 (25) as Promise behind flag[1]
27.0 (27) as Promise
Not supported Not supported Not supported 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 tracks enabling Promises by default.

See also

Document Tags and Contributors

Last updated by: jsantell,