API Docs for: 1.0 pre
Show:

Ember.RSVP.Promise Class

Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled.

Terminology

  • promise is an object or function with a then method whose behavior conforms to this specification.
  • thenable is an object or function that defines a then method.
  • value is any legal JavaScript value (including undefined, a thenable, or a promise).
  • exception is a value that is thrown using the throw statement.
  • reason is a value that indicates why a promise was rejected.
  • settled the final resting state of a promise, fulfilled or rejected.

A promise can be in one of three states: pending, fulfilled, or rejected.

Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Similarly, a rejection reason is never a thenable.

Promises can also be said to resolve a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that resolves a promise that rejects will itself reject, and a promise that resolves a promise that fulfills will itself fulfill.

Basic Usage:

var promise = new Promise(function(resolve, reject) {
  // on success
  resolve(value);

  // on failure
  reject(reason);
});

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

Advanced Usage:

Promises shine when abstracting away asynchronous interactions such as XMLHttpRequests.

function getJSON(url) {
  return new Promise(function(resolve, reject){
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url);
    xhr.onreadystatechange = handler;
    xhr.responseType = 'json';
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.send();

    function handler() {
      if (this.readyState === this.DONE) {
        if (this.status === 200) {
          resolve(this.response);
        } else {
          reject(new Error("getJSON: " + url + " failed with status: [" + this.status + "]");
        }
      }
    };
  });
}

getJSON('/posts.json').then(function(json) {
  // on fulfillment
}, function(reason) {
  // on rejection
});

Unlike callbacks, promises are great composable primitives.

Promise.all([
  getJSON('/posts'),
  getJSON('/comments')
]).then(function(values){
  values[0] // => postsJSON
  values[1] // => commentsJSON

  return values;
});

Constructor

Ember.RSVP.Promise

(
  • UNKNOWN
  • label
)

Parameters:

  • UNKNOWN Function
  • label String

    optional string for labeling the promise. Useful for tooling.

Item Index

Methods

Methods

all

(
  • entries
  • label
)
Promise static

RSVP.Promise.all accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm.

Example:

var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];

RSVP.Promise.all(promises).then(function(array){
  // The array here would be [ 1, 2, 3 ];
});

If any of the promises given to RSVP.all are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example:

Example:

var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];

RSVP.Promise.all(promises).then(function(array){
  // Code here never runs because there are rejected promises!
}, function(error) {
  // error.message === "2"
});

Parameters:

  • entries Array

    array of promises

  • label String

    optional string for labeling the promise. Useful for tooling.

Returns:

Promise:

promise that is fulfilled when all promises have been fulfilled, or rejected if any of them become rejected.

cast

(
  • object
  • label
)
Promise static

RSVP.Promise.cast coerces its argument to a promise, or returns the argument if it is already a promise which shares a constructor with the caster.

Example:

var promise = RSVP.Promise.resolve(1);
var casted = RSVP.Promise.cast(promise);

console.log(promise === casted); // true

In the case of a promise whose constructor does not match, it is assimilated. The resulting promise will fulfill or reject based on the outcome of the promise being casted.

Example:

var thennable = $.getJSON('/api/foo');
var casted = RSVP.Promise.cast(thennable);

console.log(thennable === casted); // false
console.log(casted instanceof RSVP.Promise) // true

casted.then(function(data) {
  // data is the value getJSON fulfills with
});

In the case of a non-promise, a promise which will fulfill with that value is returned.

Example:

var value = 1; // could be a number, boolean, string, undefined...
var casted = RSVP.Promise.cast(value);

console.log(value === casted); // false
console.log(casted instanceof RSVP.Promise) // true

casted.then(function(val) {
  val === value // => true
});

RSVP.Promise.cast is similar to RSVP.Promise.resolve, but RSVP.Promise.cast differs in the following ways:

  • RSVP.Promise.cast serves as a memory-efficient way of getting a promise, when you have something that could either be a promise or a value. RSVP.resolve will have the same effect but will create a new promise wrapper if the argument is a promise.
  • RSVP.Promise.cast is a way of casting incoming thenables or promise subclasses to promises of the exact class specified, so that the resulting object's then is ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise).

Parameters:

  • object Object

    to be casted

  • label String

    optional string for labeling the promise. Useful for tooling.

Returns:

Promise:

promise

catch

(
  • onRejection
  • label
)
Promise

catch is simply sugar for then(undefined, onRejection) which makes it the same as the catch block of a try/catch statement.

function findAuthor(){
  throw new Error("couldn't find that author");
}

// synchronous
try {
  findAuthor();
} catch(reason) {
  // something went wrong
}

// async with promises
findAuthor().catch(function(reason){
  // something went wrong
});

Parameters:

  • onRejection Function
  • label String

    optional string for labeling the promise. Useful for tooling.

Returns:

Promise:

finally

(
  • callback
  • label
)
Promise

finally will be invoked regardless of the promise's fate just as native try/catch/finally behaves

Synchronous example:

findAuthor() {
  if (Math.random() > 0.5) {
    throw new Error();
  }
  return new Author();
}

try {
  return findAuthor(); // succeed or fail
} catch(error) {
  return findOtherAuther();
} finally {
  // always runs
  // doesn't affect the return value
}

Asynchronous example:

findAuthor().catch(function(reason){
  return findOtherAuther();
}).finally(function(){
  // author was either found, or not
});

Parameters:

  • callback Function
  • label String

    optional string for labeling the promise. Useful for tooling.

Returns:

Promise:

race

(
  • promises
  • label
)
Promise static

RSVP.Promise.race returns a new promise which is settled in the same way as the first passed promise to settle.

Example:

var promise1 = new RSVP.Promise(function(resolve, reject){
  setTimeout(function(){
    resolve("promise 1");
  }, 200);
});

var promise2 = new RSVP.Promise(function(resolve, reject){
  setTimeout(function(){
    resolve("promise 2");
  }, 100);
});

RSVP.Promise.race([promise1, promise2]).then(function(result){
  // result === "promise 2" because it was resolved before promise1
  // was resolved.
});

RSVP.Promise.race is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the promises array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected:

var promise1 = new RSVP.Promise(function(resolve, reject){
  setTimeout(function(){
    resolve("promise 1");
  }, 200);
});

var promise2 = new RSVP.Promise(function(resolve, reject){
  setTimeout(function(){
    reject(new Error("promise 2"));
  }, 100);
});

RSVP.Promise.race([promise1, promise2]).then(function(result){
  // Code here never runs
}, function(reason){
  // reason.message === "promise2" because promise 2 became rejected before
  // promise 1 became fulfilled
});

An example real-world use case is implementing timeouts:

RSVP.Promise.race([ajax('foo.json'), timeout(5000)])

Parameters:

  • promises Array

    array of promises to observe

  • label String

    optional string for describing the promise returned. Useful for tooling.

Returns:

Promise:

a promise which settles in the same way as the first passed promise to settle.

race

(
  • array
  • label
)
static

This is a convenient alias for RSVP.Promise.race.

Parameters:

  • array Array

    Array of promises.

  • label String

    An optional label. This is useful for tooling.

reject

(
  • reason
  • label
)
Promise static

RSVP.Promise.reject returns a promise rejected with the passed reason. It is shorthand for the following:

var promise = new RSVP.Promise(function(resolve, reject){
  reject(new Error('WHOOPS'));
});

promise.then(function(value){
  // Code here doesn't run because the promise is rejected!
}, function(reason){
  // reason.message === 'WHOOPS'
});

Instead of writing the above, your code now simply becomes the following:

var promise = RSVP.Promise.reject(new Error('WHOOPS'));

promise.then(function(value){
  // Code here doesn't run because the promise is rejected!
}, function(reason){
  // reason.message === 'WHOOPS'
});

Parameters:

  • reason Any

    value that the returned promise will be rejected with.

  • label String

    optional string for identifying the returned promise. Useful for tooling.

Returns:

Promise:

a promise rejected with the given reason.

resolve

(
  • value
  • label
)
Promise static

RSVP.Promise.resolve returns a promise that will become resolved with the passed value. It is shorthand for the following:

var promise = new RSVP.Promise(function(resolve, reject){
  resolve(1);
});

promise.then(function(value){
  // value === 1
});

Instead of writing the above, your code now simply becomes the following:

var promise = RSVP.Promise.resolve(1);

promise.then(function(value){
  // value === 1
});

Parameters:

  • value Any

    value that the returned promise will be resolved with

  • label String

    optional string for identifying the returned promise. Useful for tooling.

Returns:

Promise:

a promise that will become fulfilled with the given value

then

(
  • onFulfilled
  • onRejected
  • label
)
Promise

The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled.

findUser().then(function(user){
  // user is available
}, function(reason){
  // user is unavailable, and you are given the reason why
});

Chaining

The return value of then is itself a promise. This second, "downstream" promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception.

findUser().then(function (user) {
  return user.name;
}, function (reason) {
  return "default name";
}).then(function (userName) {
  // If findUser fulfilled, userName will be the user's name, otherwise it
  // will be "default name"
});

findUser().then(function (user) {
  throw new Error("Found user, but still unhappy");
}, function (reason) {
  throw new Error("findUser rejected and we're unhappy");
}).then(function (value) {
  // never reached
}, function (reason) {
  // if findUser fulfilled, reason will be "Found user, but still unhappy".
  // If findUser rejected, reason will be "findUser rejected and we're unhappy".
});

If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.

findUser().then(function (user) {
  throw new PedagogicalException("Upstream error");
}).then(function (value) {
  // never reached
}).then(function (value) {
  // never reached
}, function (reason) {
  // The PedgagocialException is propagated all the way down to here
});

Assimilation

Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called assimilation.

findUser().then(function (user) {
  return findCommentsByAuthor(user);
}).then(function (comments) {
  // The user's comments are now available
});

If the assimliated promise rejects, then the downstream promise will also reject.

findUser().then(function (user) {
  return findCommentsByAuthor(user);
}).then(function (comments) {
  // If findCommentsByAuthor fulfills, we'll have the value here
}, function (reason) {
  // If findCommentsByAuthor rejects, we'll have the reason here
});

Simple Example

Synchronous Example

var result;

try {
  result = findResult();
  // success
} catch(reason) {
  // failure
}

Errback Example

findResult(function(result, err){
  if (err) {
    // failure
  } else {
    // success
  }
});

Promise Example;

findResult().then(function(result){
  // success
}, function(reason){
  // failure
});

Advanced Example

Synchronous Example

var author, books;

try {
  author = findAuthor();
  books  = findBooksByAuthor(author);
  // success
} catch(reason) {
  // failure
}

Errback Example


function foundBooks(books) {

}

function failure(reason) {

}

findAuthor(function(author, err){
  if (err) {
    failure(err);
    // failure
  } else {
    try {
      findBoooksByAuthor(author, function(books, err) {
        if (err) {
          failure(err);
        } else {
          try {
            foundBooks(books);
          } catch(reason) {
            failure(reason);
          }
        }
      });
    } catch(error) {
      failure(err);
    }
    // success
  }
});

Promise Example;

findAuthor().
  then(findBooksByAuthor).
  then(function(books){
    // found books
}).catch(function(reason){
  // something went wrong
});

Parameters:

  • onFulfilled Function
  • onRejected Function
  • label String

    optional string for labeling the promise. Useful for tooling.

Returns:

Promise: