Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Promise

Cameron Beccario edited this page · 3 revisions

A Promise represents the pending result of a computation that may not have completed yet.

Promise states

A Promise starts in an unresolved or pending state. For example, the Promise for a computation that hasn't yet completed is in the pending state. At some point the computation will either complete successfully, thus producing a result, or fail, either generating some sort of error or reason why it could not complete.

If the computation completes successfully, its Promise will transition to the fulfilled state, and all consumers (see below) will be notified of the actual result. In other words, their callback will be invoked and passed the result.

If the computation fails, its Promise will transition to the rejected state, and all consumers will be notified of the error or reason for the failure. In other words, their errorback will be invoked and passed the result.

Once in the fulfilled or rejected state, a Promise become immutable--neither its state nor its result (or error/reason) can be modified.

Consumers

A Promise can be safely given to any number of consumers, who can register to observe the result (or error/reason) of the promise using when(), or the promise's .then() (read why `when()` can be a better choice).

when(promise,
    function(result) {
        console.log("success: " + result);
    },
    function(reason) {
        console.log("failed: " + reason);
    }
);

or similarly with .then()

promise.then(
    function(result) {
        console.log("success: " + result);
    },
    function(reason) {
        console.log("failed: " + reason);
    }
);
Something went wrong with that request. Please try again.