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
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} let promise = new Promise((resolve) => { }); await assert.doesNotReject(promise);
the resolve function can return a value, that is consumed by the promise.then() callback
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} 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
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} let promise = new Promise((reject) => { reject(); }); await assert.rejects(promise);

an asynchronous promise

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

Links

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

Related Katas

Promise

Difficulty Level

BEGINNER

First Published

9 October 2015

Stats

8 tests to solve