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
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} const promise = new Promise((reject) => { reject(); }); await assert.rejects(promise);
via Promise.reject()
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} const promise = Promise.resolve(); await assert.rejects(promise);

Promise.all()

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()

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

Required Knowledge

Related Katas

Promise

Difficulty Level

INTERMEDIATE

First Published

15 March 2015

Stats

10 tests to solve