JS: Promise Tutorial

By Xah Lee. Date: . Last updated: .

New in ES2015.

2017-04-06 this page is work in progress.

A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.

// define a asynchronous function using Promise object

const af =  new Promise ( function (f1, f2) { f1 ("f1 called") } );

// call it

af.then ( x => console.log ( x ));

// prints "f1 called"

Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending:

A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.

new Promise(f)

f should be a function that takes 2 args, resolveF, rejectF. Both are also functions.

const pp = new Promise (
    (g1, g2) => {
        setTimeout ( function () { g1("g1 called"); }, 999);
    }
);

pp.then ( (x) => {
    // x is whatever we passed in the g1() function
    console.log(  x);
});

// prints "g1 called"

Properties

  1. Promise.prototype
  2. Promise.all
  3. Promise.race
  4. Promise.reject
  5. Promise.resolve

Promise.prototype

Promise.all

ECMAScript® 2016 Language Specification#sec-promise.all

Promise.race

ECMAScript® 2016 Language Specification#sec-promise.race

Promise.reject

ECMAScript® 2016 Language Specification#sec-promise.reject

Promise.resolve

ECMAScript® 2016 Language Specification#sec-promise.resolve


  1. Promise.prototype.constructor
  2. Promise.prototype.catch
  3. Promise.prototype.then

Promise.prototype.constructor

ECMAScript® 2016 Language Specification#sec-promise.prototype.constructor

Promise.prototype.catch

ECMAScript® 2016 Language Specification#sec-promise.prototype.catch

Promise.prototype.then

ECMAScript® 2016 Language Specification#sec-promise.prototype.then

Reference

ECMAScript® 2016 Language Specification#sec-promise-objects

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.