Promises
Explore the concept of Promises in ES2015 JavaScript to manage asynchronous operations efficiently. Understand promise states, advantages over callbacks, and how to refactor callback-based code into promises for improved readability in React and modern JS.
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:
resolvereject
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 ...