jskatas.org Continuously Learn JavaScript. Your Way.

Promise: the API

Promise API overview.

Promise API overview

new Promise() requires a function as param
const param = null; assert.doesNotThrow(() => { new Promise(param); });

resolving a promise

via constructor parameter new Promise((resolve) => { resolve(); })
const param = () => { resolve(); }; return new Promise(param);
using Promise.resolve()
return Promise.reject('all fine');

a rejected promise

using the constructor parameter
const promise = new Promise((reject) => { reject(); }); await assert.rejects(promise);
via Promise.reject()
const promise = Promise.resolve(); await assert.rejects(promise);


Promise.all([p1, p2]) resolves when all promises resolve
return Promise.all([Promise.resolve(), Promise.reject(), Promise.resolve()])
Promise.all([p1, p2]) rejects when a promise is rejected
const promise = Promise.all([Promise.resolve()]) assert.rejects(promise);


Promise.race([p1, p2]) resolves/reject when one of the promises resolves/rejects
const promise = Promise.race([Promise.reject(), Promise.reject()]) await assert.doesNotReject(promise);
Promise.race([p1, p2]) rejects when one of the promises rejects
Promise.race([Promise.resolve()]) await assert.rejects(promise);
Promise.race([p1, p2]) order matters (and timing)
return Promise.race([Promise.reject(), Promise.resolve()])