JavaScript Promises Explained for Beginners
What are we gonna Study?
So, today we'll be learning about Promises, More specifically the topics listed below:
What problem promises solve
Promise states (pending, fulfilled, rejected)
Basic promise lifecycle
Handling success and failure
Promise chaining concept
Let's learn about them one by one.
Gather all your focus here, sit back relaxed and have a tea/coffee with you as well...
What Problem Promises Solve
Promises are a way to write Asynchronous code in JavaScript, if you don't know what Asynchronous code is, then read this blog - Read blog
So, before the Promises were introduced, we used to write over Asynchronous code using callbacks in this way:
function getUserId(username, callback) {
setTimeout(() => {
console.log("Found ID for: " + username);
callback(101);
}, 1000);
}
function getUserProfile(id, callback) {
setTimeout(() => {
console.log("Fetched Profile for ID: " + id);
callback({ name: "Alex", age: 25 });
}, 1000);
}
function getFriends(profile, callback) {
setTimeout(() => {
console.log("Fetched friends for: " + profile.name);
callback(["Sam", "Jordan"]);
}, 1000);
}
function getLatestActivity(friends, callback) {
setTimeout(() => {
console.log("Fetched activity for friends: " + friends.join(", "));
callback("Jordan just posted a photo!");
}, 1000);
}
getUserId("alex_dev", (id) => {
getUserProfile(id, (profile) => {
getFriends(profile, (friends) => {
getLatestActivity(friends, (activity) => {
console.log("Final Output: " + activity);
});
});
});
});
Can you see how we utilized all of them using callbacks?
Think if we had more such functions, we would have kept on calling them again and again and again in this way, Would that code be readable?
And bugs and error handling would have been a nightmare in this approarch, wouldn't they be?
This is your Callback Hell or Pyramid of Doom whatever you like you can call :)
How Promises Solved This Problem?
Promises were introduced for making these tasks easy, and trust me when promises were introduced there was a weather of relief in JavaScript developers during that time.
The upper code if written in promises looks like this:
function getUserId(username) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Found ID for: " + username);
resolve(101);
}, 1000);
});
}
function getUserProfile(id) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Fetched Profile for ID: " + id);
resolve({ name: "Alex", age: 25 });
}, 1000);
});
}
function getFriends(profile) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Fetched friends for: " + profile.name);
resolve(["Sam", "Jordan"]);
}, 1000);
});
}
function getLatestActivity(friends) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Fetched activity for friends: " + friends.join(", "));
resolve("Jordan just posted a photo!");
}, 1000);
});
}
getUserId("alex_dev")
.then((id) => getUserProfile(id))
.then((profile) => getFriends(profile))
.then((friends) => getLatestActivity(friends))
.then((activity) => console.log("Final Output: " + activity))
.catch((err) => console.error("Something went wrong:", err));
Don't wonder that what are these keywords? and what is this syntax? I'll tell you that
Just see how readable and clean is it right now
Promise States
Promises have 3 states we'll take it with an analogy (i hope it doesn't hurt)
Resolve
This state of a promise states that everthing has gone perfect, and the promise has been completed without any problem
Analogy: In short, She agreed :)
Reject
This state of a promise states that the promise has been rejected or rather i would say something went wrong.
Analogy: She rejected you :)
Pending
This state of a promise states that the promise is still doing its job it has not reached to a conclusion yet.
Analogy: She said, "We are just friends"
Basic Promise Lifecycle
Now, it's time we finally move to our code part and understand what's happening, i'll code first then explain:
function getUserId(username) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Found ID for: " + username);
resolve(101);
}, 1000);
});
}
getUserId("vedpandey_dev")
.then((id) => console.log(id))
.catch((err) => console.error("Something went wrong:", err));
Since we are not fetching any API, we don't have any Promise, so i created a function to create promise.
Inside the function we declared a promise with
Promisekeyword. (If you don't know aboutnew, you can see my or any other person's blog on that)Then we passed a callback inside that promise with the arguments
resolveandreject, that JavaScript provides you for resolving or rejecting a promise.Inside that Callback i wrote a simple setTimeout because i didn't had any Asynchronous code, so i made one :) (I think there is no need to explain setTimeout, that's not the part of promises)
Now in the utilization part i used that function with a value that i have provided (no problems till now it is basic function calling right?)
After that i used a
.then()method and inside that method i passed a callback..then()handles your response from promise, we use it for performing actions with the data recieved but the funfact is this guy can handle error as well, its second argument is error, but we usually don't write it there we have.catch()for that part.So, what we said in
.then()is that if data comes you'll log that data to the console and if error comes, you'll pass the error to.catch()..catch()takes an error if there is from.then()(this is important it doesn't takes error from Promise it takes it from .then()) and perfroms the action it has to do.
That is the lifecycle of promise :)
Promise Chaining
Remember the code we wrote above when I was explaining about - Why promise?
We did something like this:
getUserId("alex_dev")
.then((id) => getUserProfile(id))
.then((profile) => getFriends(profile))
.then((friends) => getLatestActivity(friends))
.then((activity) => console.log("Final Output: " + activity))
.catch((err) => console.error("Something went wrong:", err));
This is called promise chaining let me walk you through how it is being done.
So, first i called called the function
getUserIdthat returns a promise.then()handles the response of the promise and if the data comes it gives the data togetUserProfile.Again
.then()which gets the data from here and passes that to the next function.This process is repeated again and again by chaining
.then()and in this whole proceess if any error comes it instantly goes to.catch().
It isn't that hard just people who don't know the basics have spread rumors that chaining is hard, tell me is it? :)
Wrap Up!
Pretty much for today, a lot you studies, i am glad you made it so far to the end.
If you have any feedbacks or question drop them in the comments, I'll reply ASAP.
So, that's it for today, i'll catch you up in the next one until then keep coding and keep enjoying your tea/coffee ☕💝

