Promises
Learn about promises, how they have been revamped with ES2015, and how to use them in place of a callback.
We'll cover the following...
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:
resolve
reject
An executor function can also take any of the following three states:
- pending
- fulfilled
- 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 ...