JS: Promise Tutorial
(new in JS: ECMAScript 2015)
xtodo 2025-06-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.
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 fulfilled if
p.then(f, r)
will immediately enqueue a Job to call the functionf
. - p is rejected if
p.then(f, r)
will immediately enqueue a Job to call the functionr
. - p is pending if it is neither fulfilled nor rejected.
p is settled if it is not 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.
- An unresolved promise is always in the pending state.
- A resolved promise may be pending, fulfilled or rejected.
Properties
Promise.prototype
Promise.all
Promise.race
Promise.reject
Promise.resolve
Promise.prototype
Promise.all
Promise.race
Promise.reject
Promise.resolve
Promise.prototype.constructor
Promise.prototype.catch
Promise.prototype.then