Promises

Learn about promises, how they have been revamped with ES2015, and how to use them in place of a callback.

Introduction

Promises are not an exclusively new concept in JavaScript. However, with ES2015, they have been standardized and for the first time may be used without any other additional libraries. Promises allow for asynchronous development by linearizing with callbacks. A promise takes in an executor function, which again takes two arguments:

  1. resolve
  2. reject

An executor function can also take any of the following three states:

  1. pending
  2. fulfilled
  3. rejected

Let’s go through these states one by one.

Pending

The initial state of a promise is always pending.

Fulfilled

If the executor function is successful, meaning resolve, the status of the promise changes from “pending” to “fulfilled”. You can then react to this state with .then(). Since resolve is passed to the executor function, the then() part will execute.

Rejected

If the executor function is unsuccessful, meaning reject, the status of the promise changes from “pending” to “rejected”. You can then react to this state with .catch(). Since reject is passed to the executor function, all ...