Promises in JavaScript are a way to handle asynchronous code execution. They provide a way to write asynchronous code that is more readable and easier to understand.
In case you are a video person, you can check out the video tutorial here:
If you prefer reading, then let’s continue. So, let’s start by creating a promise. The syntax for creating a promise is as follows:
let promise = new Promise((resolve, reject) => {
// code to execute
});
The promise constructor takes a single argument, which is a function. This function is known as the “executor” function and it is responsible for executing the asynchronous code. The executor function takes two arguments: resolve and reject.
The resolve function is used to signal that the promise has been fulfilled, and the reject function is used to signal that the promise has been rejected.
Example
For example, let’s say we want to create a promise that returns the value of a number after 2 seconds.
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(10);
}, 2000);
});
promise.then((value) => {
console.log(value); // prints 10
});
promise.catch((error) => { console.log(error); });
promise.finally(() => { console.log('done'); });
Promises can also be chained together to handle multiple asynchronous operations in a sequential manner.
For example, let’s say we have a function that returns a promise that fetches a user’s name from an API. Here I have used the setTimeout() method to simulate the asynchronous event, however in reality we will be getting the data from an API call (we will see that later in the post):
function getUserName() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Ashish');
}, 2000);
});
}
getUserName().then((name) => {
console.log(name);
}).catch((error) => {
console.log(error);
}).finally(() => {
console.log("completed");
})
//Ashish
//completed
Promises in JavaScript have three states:
- Pending: initial state, neither fulfilled nor rejected.
- Fulfilled: successful operation
- Rejected: failed operation
Promise object has a property called state that returns the current state of the promise.
Promises are widely used in modern web development and are important to understand for anyone working with JavaScript. It is also important to note that promises are not just limited to handle only asynchronous operations, but also can be used in synchronous operations as well, so it depends on the use case, however I don’t know why someone will use promises for synchronous operations but I want you to know that this is possible. Also, it’s a good practice to always provide a .catch() block at the end of the chain of .then() blocks, in order to handle any errors that may occur during the execution of asynchronous code.
Real-life practical example.
fetch('https://dummyjson.com/products')
.then(res => res.json())
.then(console.log);
//{products: Array(30), total: 100, skip: 0, limit: 30}
Now this is a simple, but excellent example to understand the basics of promises in JavaScript. The fetch API always returns a promise. So, we are using the .then method to handle the result of the promise. Inside the then method we have passed in a function parameter `res` which holds the response from the promise. After that we are using the .json() method which is available for the fetch API’s response object. It is used to extract the JSON data from the response received by fetch call.
Next as you can see in the line no 3 we have chained another .then method. Now you need to know that .then method always returns a promise which allows us to chain further then method. So here, the .then at line no 2 returns a promise containing the JSON data which is handled by then at line no 3. The console.log statement at line no 3 then prints the json data onto the console.
Now if you want to see an example for rejected promise, just change the url inside the fetch call. I have changed “dummyjson” to “dummyjso” here to show you the results.
fetch('https://dummyjso.com/products')
.then(res => res.json())
.catch(console.log);
//TypeError: Failed to fetch
The functioning of this code is same as above, the only difference is that this time we get an error and that error is received by the catch block on line no. 3 and is logged on the console.
What next?
What we have learned about the promises here is just the tip of the iceberg, there are many different ways and many different syntax in which we can use promises in our project. I hope this post would have given you a starting point to understand the absolute basics of using promises in JavaScript. Next I want you to go the official docs and try to understand Promise in detail. Don’t worry if you don’t understand something in one go. Just come back here and comment where exactly you are stuck and I will try my best to help.
We can use the even more modern async/await syntax which was introduced in ES7 to easily handle asynchronous code. We will learn more on that in subsequent post. You can check the recent posts here.
If you are preparing for a job interview, you can check out more JavaScript Interview Questions here.
Share this:
- Click to share on WhatsApp (Opens in new window)
- Click to share on Twitter (Opens in new window)
- Click to share on Facebook (Opens in new window)
- More
- Click to print (Opens in new window)
- Click to email a link to a friend (Opens in new window)
- Click to share on LinkedIn (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on Pocket (Opens in new window)
- Click to share on Telegram (Opens in new window)
- Click to share on Tumblr (Opens in new window)
- Click to share on Pinterest (Opens in new window)