JS: Promise Tutorial

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

xtodo 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.

new Promise(executorF)

executorF should be a function that takes 2 args, fResolve, fReject. Both are also functions.

const execF = (fResolve, fReject) => {
  setTimeout(() => {
    fResolve("fResolve called");
  }, 999);
};

const pms = new Promise(execF);

pms.then((x) => {
  // x is whatever we passed in the fResolve() function
  console.log(x);
});
// fResolve called
// define a asynchronous function using Promise object

const pms = new Promise((f1, f2) => {
  f1("f1 called");
});

// call it
pms.then((x) => console.log(x));

// prints "f1 called"

States of Promise

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

p is settled if it is not pending.


Properties

Promise.all

Promise.race

Promise.reject

Promise.resolve

Promise.prototype

Promise.prototype.constructor

Promise.prototype.catch

Promise.prototype.then