jskatas.org Continuously Learn JavaScript. Your Way.

Promise: basics

A promise represents an operation that hasn`t completed yet, but is expected in the future.

a Promise represents an operation that hasn't completed yet, but is expected in the future

Promise is a global function
const expectedType = '???'; assert.equal(typeof Promise, expectedType);

the constructor

instantiating it without params throws
const fn = () => { Promise } assert.throws(fn);
expects a function as parameter
const param = null; assert.doesNotThrow(() => { new Promise(param); });

simplest promises

resolve a promise by calling the resolve function given as first parameter
let promise = new Promise((resolve) => { }); await assert.doesNotReject(promise);
the resolve function can return a value, that is consumed by the promise.then() callback
let promise = new Promise((resolve) => { resolve(); }); await assert.doesNotReject(promise); assert.equal(await promise, 42);
rejecting a promise is done by calling the callback given as 2nd parameter
let promise = new Promise((reject) => { reject(); }); await assert.rejects(promise);

an asynchronous promise

can resolve later, also by calling the first callback
let promise = new Promise(() => { setTimeout(() => resolve(), 100); }); await assert.doesNotReject(promise);
reject it at some later point in time, calling the 2nd callback
let promise = new Promise((reject) => { setTimeout(() => reject(), 100); }); await assert.rejects(promise);

test library (mocha here) support for promises

just returning the promise makes the test library check that the promise resolves
let promise = new Promise((reject, resolve) => { resolve(); }); // return the promise to mocha, it has the checking for promise resolving built in, when it receives a promise return promise;

Links

A well understandable description of the states a promise can be in.