JavaScript Promises
A Promise is a one-time guarantee of a future value. Think of it as a Promise in the real world. When I was in a high-school, I asked my mom to get me a two-wheeler, and she said, she promise if I get a good grade in high-school, she will certainly buy me a two-wheeler very next day of my result. So, that Promise is not a two-wheeler itself. It doesn’t mean a yes, that ok there is my two-wheeler. It is just that one day in future she will buy me a two-wheeler.
We all know, not all the promises are kept. Sometimes, that Promise might get resolved, or rejected. Guess what, I scored very well in high-school and my mom just said no and gave me another promise that I will have that in future. Finally, got one now lately its my car😀
Let’s talk about Promises in terms of JavaScript. The mental model for promises and how they relates to the asynchronous code.
Let’s pass the request using a promise using axios.
.axios is a promise based library for making HTTP requests. similar to the jQuery AJAX methods, but doesn’t use callback pattern.
However, What exactly is a Promise?
Promises in JavaScript are objects, which can be in one of three potential states:
- Pending — It doesn’t yet have a value yet
- Resolved — It has successfully obtained a value
- Rejected — It failed to obtain a value for some reason
In the context of making an API call, Promise will be pending if something went wrong, when we haven’t heard back from the API, immediately after sending the request.
The Promise will be resolved if we get the data back, if we get 200 status code and we have the information as it is resolved.
Let’s say if my internet or power is completely shut down, we will get 400 status code, that promise will be rejected.
So, how do we access the value ??
- The way to have an access to resolved or rejected value is to chain a method on the end of the Promise.
.then and .catch
promises provide a .then and .catch, which both accepts callbacks.
- The callback to .then will run if the Promise is resolved, and has access to the promise’s resolved value.
- The callback to .catch will run if the Promise is rejected, and typically has access to the some reason behind the rejection.
When reading about promises, you’ll often see a term, called .thenable, which is simply any object or let’s say a function that has a then method defined on it.
All promises are thenables, but not all thenables are promises😂
Let’s see the example of a thenable that isn’t a promise:
Promise Chaining
- When you call .then a promise, you can return new promise in the callback. This means you can chain multiple asynchronous operations together with several .then calls.
- While using this pattern, you need .catch at the end only once, and also you don’t have to catch every promise individually.
A Promise represents a pending value means a guarantee that the value may be either resolved or rejected. Standard promises also have a .then() method, which takes a callback of the resolved value, which can be chained. Standard promises also have a .catch() method, which takes a callback of the rejected value and this can listed only at once at the end of the .then chain. Axios and jQuery’s AJAX methods both use promises.
So, we have seen the promises are coming back from axios methods callbacks and promises. Now that we know what a difference promises can make assuming that we are chaining them with .then and .catch and nesting them inside of each other which does not make a difference in real. but, if we return the promises and chain them together chain the .then we can have a much flatter and readable piece of code.
Now, you might be wondering why do we have Promises?
Promises gives the ability to write clean code and avoids the call-back hell. In addition, Promises allows errors to be passed down the chain and handled in one common place without having the layers of manual error handling. If we have more nested requests things may get out of control.
Example
Built in Promise function
There are several helper methods that live on Promise.
- Promise.all
- Promise.race
- Promise.reject
- Promise.resolve
Promise.all accepts an array of promises and returns a new Promise. This new Promise will resolve when every Promise in the array resolves, and will be rejected if any Promise from the array is rejected. It is extremely useful to send several independent request in parallel.
Let’s look at the example below:
- Promise.race accepts an array of promises and returns a new Promise. This new promise will resolve or reject as soon as one Promise in the array resolves or rejects.
Here’s the example of it:
- Promise.resolve
Promise.resolve accepts a value and returns a promise which has immediately resolved to the value passes in.
Let’s look at the example of it:
- Promise.reject
Promise.reject accepts a value and returns a promise which has immediately rejected to the value passed in.
Building our own Promises
We can return our own promise object and make our own promises.
Use new keyword alongside Promise(P is uppercase) to make a new promise object. When we pass in to that promise is a single function as an argument. The function accepts two different functions as an arguments which is, resolve and reject. To resolve the promise eventually we execute resolve and to reject the promise we execute the second argument reject.
Let’s look at Asynchronous function pattern for promises with this example:
Conclusion:
A promise is a one time guarantee of the future value. Promise is a part of JavaScript of ES2015. It provides a clear and consistent way to handle the callbacks. You can make your promises using Promise with new keyword, but the syntax isn’t intuitive. You can chain multiple promises together to consume the results of the promises.
Thanks for reading this article, This is my first article where I shared my knowledge. Feel free to share your thoughts. Happy learning😊.