Effortlessly Understanding JavaScript Promises

Effortlessly Understanding JavaScript Promises

Promises! A love story

·

6 min read

Promises in JavaScript can be a tricky concept to grasp, but with the right understanding, it can become a powerful tool in your programming arsenal. By reading this article, you'll gain a deeper understanding of promises and how they work, making it a skill you'll never forget. We'll explore the concept of promises through the relatable story of two lovers, Raj and Simran.


Story Time

The name Raj, you might have heard it before he works in a company as a Software Engineer and Simran is her colleague. Wait! Did you think Raj and Simran must be traveling around Europe? No, they are modern-day Raj and Simran, and they have bills to pay, so they have corporate jobs. One day, Simran has to give a presentation to the client and she saved the presentation on her google drive. But in the morning, she realizes she can't log in to her google account.

Simran:- Wait! Has someone hacked my google account? OMG, I have to give the presentation to the client in 30 minutes, what will happen now?

(Raj's cubicle is next to Simran's, so he hears everything)

Raj:- I'm here for you (mein hoon na). I promise you that I will recover your account before your presentation.

(Simran, feeling relieved and grateful, also starts to develop affection towards Raj for his help. Now, Raj's promise of recovering Simran's account has two possible outcomes. Either he will fulfill his promise and Simran will be able to give her presentation to the client, or if he doesn't, Simran's image in front of the client will be compromised. Exactly 25 minutes later, Raj successfully recovers Simran's google account using his technical skills.)

Simran:- OMG thank you so much, Raj. I have to go to the conference room with my laptop quickly, I'll see you after the presentation.

(Simran's presentation goes really well and the client is pleased with it. After the presentation, Simran thanks Raj once again, and the two of them decide to go on a coffee date to celebrate.)

Please do not read this code now, read it after you have read the entire article.

recoverSimranAccount()
  .then((account) => {
    console.log("Simran got her account :" + account);
  })
  .catch((msg) => console.log("sadly! simran could'nt give presentation"));

function recoverSimranAccount() {
  const promiseOfRaj = new Promise((resolve) => {
    //raj trying to recover account...
    //raj trying to recover account...
    //raj trying to recover account...
    //raj trying to recover account...
    //raj trying to recover account...
    resolve("password");
  });
  return promiseOfRaj;
}

Promises in Javascript

Let's now see the technical definition of a promise in Javascript:-

  • A promise is an object which represents the eventual completion or failure of an asynchronous task.

  • Or in other words, we can say that a promise object carries information about the outcome of an asynchronous operation.

  • We use promises to handle the asynchronous operations and the tasks we want to perform after it has been done successfully or unsuccessfully.

  • For example, Showing the user videos after they have been fetched from the youtube server or showing an error or retry button if it failed to fetch videos due to any possible reasons.

There are three states possible of a promise which are:-

  1. pending

  2. fulfilled

  3. rejected

Wait! but how exactly does this "promise" object looks like? Let's have a look...

As we can see a promise object has 3 properties, which are:-

  1. Prototype - it has then(),catch() and finally() methods.

  2. PromiseState - pending, fulfilled and rejected.

  3. PromiseResult - It contains the response returned by the promise.

We'll see each of these properties in action in the subsequent sections.


Consuming a Promise

Let's first see how to consume a promise through a code snippet:-

const URL = "https://jsonplaceholder.typicode.com/users";
const promise = fetch(URL);

promise
  .then((data) => console.log("data fetched successfully...",data))
  .catch((error) => console.log("Something went wrong!",error));

In the above example, I am fetching dummy users' data from a fake API. I am using the fetch() method to make an HTTP call, this method returns a promise object. Now there are two possible outcomes of this async operation either it'll be completed successfully and we'll get the users' data or it'll not be completed and we'll get an error. Ideally, we want to do certain things on either of the outcomes.

We have two methods on a promise object then() and catch() . Whatever we want to do after our async operation has been completed successfully we'll put it in a callback function and provide/attach it to the then() method, Similarly whatever we want to do if our async operation fails we'll wrap it in a callback function and attach it to the catch() method.

Both of these methods expect a callback function as an argument to be passed, and the callback function will receive a data object in case of then() and error object in case of catch(). We'll see in the next section exactly what is received in these callback functions.


Creating a Promise

Alright! now we know how to consume a promise, but how do we create one? let's have a look at the below code snippet.

const num1 = 8;
const num2 = 7;
const response = isEven(num1);

response
.then((data) => console.log(data))
.catch((error) => console.log(error));

function isEven(number) {
  const promise = new Promise((resolve, reject) => {
    if (number % 2 === 0) resolve(`Boom! ${number} is an Even number`);
    else reject(`${number} is an odd number`);
  });
  return promise;
}
  • We can create a promise by invoking the promise constructor new Promise().

  • It expects a callback function as an argument that has two parameters resolve and reject.

  • resolve and reject are methods, Whenever the given responsibility has been completed successfully we'll call the resolve method and if it is not completed we'll call the reject method.

Key Points

  • Anything passed to resolve() will be received in the callback function's argument of then() method.

  • Anything passed to reject() will be received in the callback function's argument of catch() method.

So in the above example let's assume that isEven(number) is an API that receives a number and returns a success message if it is an even number and an error message if it is an odd number. So as I called isEven(number) with num1=8 the promise will be resolved and we'll receive "Boom! 8 is an Even number" in the callback function's argument of then() method.

Now I would request you to play around with the above code snippet and try passing num2 to isEven(number), and I am pretty sure you know exactly what is going to be the output.


Conclusion

So that was all from my side on promises in Javascript, Isn't it a powerful tool to interact with the asynchronous world? Do you feel confident about it now? I would love to hear your thoughts and feedback on this.