Introduction

suggest change

A Promise object represents an operation which has produced or will eventually produce a value. Promises provide a robust way to wrap the (possibly pending) result of asynchronous work, mitigating the problem of deeply nested callbacks (known as “callback hell”).

States and control flow

A promise can be in one of three states:

A promise is settled when it is fulfilled or rejected. Once it is settled, its state does not change. Resolved is not a synonym: resolving can lock a promise onto another still-pending promise, so a resolved promise can still be pending. The then and catch methods of a promise can be used to attach callbacks that execute when it is settled. These callbacks are invoked with the fulfillment value and rejection reason, respectively.

The original state diagram is not included. A copy was previously hosted at https://drive.google.com/file/d/0B9QwORzdBQHXNkR1azQ3OEF4QlE/view?usp=sharing.

Example

const promise = new Promise((resolve, reject) => {
    // Perform some work (possibly asynchronous)
    // ...

    const success = true; // stand-in for the operation's result
    const value = "value";
    const message = "failed";
    if (success) {
        resolve(value);
    } else {
        // The reason is traditionally an Error object, although
        // this is not required or enforced.
        const reason = new Error(message);
        reject(reason);
        // Throwing instead of reject also rejects, but only if the
        // promise is not already settled. Do not do both.
    }
});

The then and catch methods can be used to attach fulfillment and rejection callbacks:

promise.then(value => {
    // Work has completed successfully,
    // promise has been fulfilled with "value"
}).catch(reason => {
    // Something went wrong,
    // promise has been rejected with "reason"
});

Note: then and catch attached separately to the same promise are siblings. A throw inside the fulfillment handler rejects the promise returned by then. The sibling catch does not see that rejection, so it can become an unhandled rejection. Attach the next handler to the promise returned by the previous then or catch.

Alternatively, both callbacks can be attached in a single call to then:

promise.then(onFulfilled, onRejected);

Attaching callbacks to a promise that has already been settled will immediately place them in the microtask queue, and they will be invoked “as soon as possible” (i.e. immediately after the currently executing script). It is not necessary to check the state of the promise before attaching callbacks, unlike with many other event-emitting implementations.

Live demo

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents