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.

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

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

  • Promise is a global function

the constructor

  • instantiating it without params throws
  • expects a function as parameter

simplest promises

  • resolve a promise by calling the resolve function given as first parameter
  • the resolve function can return a value, that is consumed by the promise.then() callback
  • rejecting a promise is done by calling the callback given as 2nd parameter

an asynchronous promise

  • can resolve later, also by calling the first callback
  • reject it at some later point in time, calling the 2nd callback

test library (mocha here) support for promises

  • just returning the promise makes the test library check that the promise resolves

Links

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