Skip to main content

Command Palette

Search for a command to run...

JavaScript Promises Explained for Beginners

Updated
6 min read

What are we gonna Study?

So, today we'll be learning about Promises, More specifically the topics listed below:

  1. What problem promises solve

  2. Promise states (pending, fulfilled, rejected)

  3. Basic promise lifecycle

  4. Handling success and failure

  5. 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 Promise keyword. (If you don't know about new , you can see my or any other person's blog on that)

  • Then we passed a callback inside that promise with the arguments resolve and reject, 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 getUserId that returns a promise

  • .then() handles the response of the promise and if the data comes it gives the data to getUserProfile.

  • 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 ☕💝

JavaScript: Everything you should know

Part 19 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Understanding the this Keyword in JavaScript

Today in this blog I'll be covering the most important topic of JavaScript OOPS and that is this keyword... A comprehensive list of the topics is given below: What this represents this in global con

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!