JS: Promise Tutorial
New in JS2015.
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 p is fulfilled if p.then(f, r) will immediately enqueue a Job to call the function f.
- A promise p is rejected if p.then(f, r) will immediately enqueue a Job to call the function r.
- A promise is pending if it is neither fulfilled nor rejected.
- A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.
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
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