Promise Day-Feb 11th- Promises with my Lover JS (JavaScript)

Photo by Icons8 Team on Unsplash

Promise Day-Feb 11th- Promises with my Lover JS (JavaScript)

Hi folks, as we all know today is promise day, so today I will speak about promises in my lover JS (JavaScript) life.You know today js has come to me and said me this - "Hey , your last promise(which you had given to me that you will gift me a necklace) is still in pending state, either you fulfilled it or rejected it(with a reason), but at least let me know,I can't keep on waiting.Although I am doing and busy at my own works, but whenever I remind of your promise, I am getting its in the pending state, only.Whats happening?"

So you know here what's happening ? Did you folks , getting any idea? Let me tell you.

A promise in js is an object that we can use to handle asynchronous operations ie. the results of the asynchronous operation can be encapsulated inside a promise.

For understanding asynchronous ,let's understand synchronous first. In synchronous code, operation are performed one at a time. Synchronous code will block the further execution of the remaining code until it finishes the current one.

And you know what, since that day, we had a planned dinner already, so instead of myself going out , I just call my friend (who had a jwellery shop) and told him to send me the necklace for js. If we consider it synchronous code, then we have to wait until my friend didn't send the necklace to our home. It simply means that we need to wait for an operation in progress to finish(in this case getNecklaceFromShop function execution), in order to start the next one(in this case, dinner date).And this will cause our dinner date to wait ,that I didn't want.Who will want that?

Synchronous code example

function getNecklaceFromShop() {
  //adding a long while loop to show you
  //this will take long time
  //ie. getNecklaceFromShop will take huge time
  //and till the time this function doesn't return anything
  //the next code (i.e our planned dinner will not happen)
  //and this shows synchronous nature of this code
  //since it blocks the rest of code to execute (specially our planned dinner)
  //and then we don't have the dinner at the right time as we have
  //to keep on waiting (blocking nature of code) till the necklace received

  let timeTaken = 0;
  while (timeTaken < 1000000000) {
    timeTaken++;
  }

  console.log("I will go to the shop");
  console.log("I will bought the necklace");
  console.log("and return to the home with necklace");
  return "Js, here's your necklace";
}

//Js asking for a necklace
console.log("Js to me - Hey honey! I want necklace as a gift.");

//I am assigning a function and this function I will call my friend and he will send the necklace back to home
let necklaceStatement = getNecklaceFromShop();

//the next lines in the code will not run till getNecklaceFromShop() executed due to synchronous nature of the code

console.log(necklaceStatement);
console.log("Let's have the dinner.");
console.log("Oh! the dinner is too cold now.No fun");

Output of the above code will be - Js to me - Hey honey! I want necklace as a gift. I will go to the shop. I will bought the necklace and return to the home with necklace. Js, here's your necklace. Let's have the dinner. Oh! the dinner is too cold now. No fun.

Hope you understand, synchronous code means here, at least I know since it ruins my dinner date to js. And you know, Javascript is default synchronous nature. So, as you understand synchronous ,lets move to asynchronous meaning.

Asynchronous means here not occuring at the same time, since I can't just straight away bring a necklace for her after getting an immediate demand for her since we had a planned dinner and I didn't want to ruin that. In asynchronous code, the next operation can be started before the previous oepration done finishing the execution and in this way we can handle multiple requests and hence it's depicts non-blocking nature of the code and increases the overall efficiency. Since js by default is synchronous nature, so we used "callbacks or promises or async-await" (all these terms) to indicates the async behaivour in our code. It just like when we send an axios or fetch request to a particular server , instead of sitting there only and waiting for the response , we just moved on to next task and whenever that asynchronous code returns the result, depend on our availablity, we will take the result from that.

So coming back to Promise in Javascript, it is an object that we can use to handle asynchronous operations ie. the results of the asynchronous operation can be encapsulated inside a promise. Each promise has state , which can contain any of three value - pending state(this state represents the intial state of the promise, it attaches with the newly created promise).The promise maintains the pending state till the time asynchronous operation is in progress.And depending on how the asynchronous operation completes, the promise state changes to either fulfilled (when the asynchronous operation completed sucessfully, in short the promise is fulfilled) or rejected (when the asynchronous operation doesn't completed sucessfully i.e. it got failed, in short the promise is rejected, not fulfilled).

In JavaScript, we can create a promise object using a special constructor called Promise , just like the below code. The Promise() constructor also takes a function as an argument. The function also accepts two callbacks- resolve() and reject(). If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.

The then() method is used with the callback when the promise is successfully fulfilled or resolved.The catch() method is used with the callback when the promise is rejected or if an error occurs.

const promise = new Promise((resolve, reject) => {
  // indicating Async operations  here
  if (asyncOperationDone) {
    resolve(value); // if async operation, successfully done
  } else {
    reject(error);  // if async operation, some  error occurred
  }
});
promise.then(()=>{
  console.log("this will be executed when promise is fulfilled");
}).catch(()=>{
  console.log("this will be executed when promise is rejected or error occured.");
})

Let me define a function named myPromiseToJs

//here my function will return a Promise object
function myPromiseToJs() {
  return new Promise(function (resolve, reject) {
    //to bring async behaviour using setTimeout so this promise execution will take sometime
    setTimeout(() => {
      let isBoughtNecklace = null;
      // if (isBoughtNecklace) {
      //   resolve("Hey Js , here is your necklace.");
      // } else {
      //   reject(
      //     "Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
      //   );
      // }
    }, 2000);
  });
}

//Js asking for a necklace
console.log("Js to me - Hey honey! I want necklace as a gift.");

//I am invoking myPromiseToJs() function which will return a promise object, since asynchronous nature has added in the myPromiseToJs function through setTimeout function , so it will not block the execution of code here and next code ie. "Let's have a dinner" and rest messages will be printed.

const promise = myPromiseToJs();
console.log(promise); //if I print promise here it will print pending state, since every Promise begins with pending state only, it maintains the pending state till the asynchronous operation doesn't completed.

promise
  .then((message) => {
    console.log(message);
  })
  .catch((message) => {
    console.log(message);
  });

console.log("Let's have a dinner");
console.log("Wow, dinner is too awesome");

Output of the above code will be-

Js to me - Hey honey! I want necklace as a gift. Promise { pending }. Let's have a dinner Wow, dinner is too awesome.

You see in the above code, the promise is showing pending since intially its in pending state only while creation , and I didn't resolve or reject the promise so thats why no, then or catch block executed. So don't make Js more angry, let's change the promise state to ...

function myPromiseToJs() {
  return new Promise(function (resolve, reject) {
    //to bring async behaviour using setTimeout so this promise execution will take sometime
    setTimeout(() => {
      let isBoughtNecklace = false;
      if (isBoughtNecklace) {
        resolve("Hey Js , here is your necklace.");
      } else {
        reject(
          "Sorry Js, I can't brought a necklace for you.Next time I will surely gift you."
        );
      }
    }, 2000);
  });
}
//Js asking for a necklace
console.log("Js to me - Hey honey! I want necklace as a gift.");

//I am invoking myPromiseToJs() function which will return a promise object, since asynchronous nature has added in the myPromiseToJs function through setTimeout function , so it will not block the execution of code here and next code ie. "Let's have a dinner" and rest messages will be printed.

const promise = myPromiseToJs();
console.log(promise); //if I print promise here it will print pending state, since every Promise begins with pending state only, it maintains the pending state till the asynchronous operation doesn't completed.

promise
  .then((message) => {
    console.log(message);
  })
  .catch((message) => {
    console.log(message);
  });

console.log("Let's have a dinner");
console.log("Wow, dinner is too awesome");

And this time the output is-

Js to me - Hey honey! I want necklace as a gift. Promise { pending } Let's have a dinner Wow, dinner is too awesome Sorry Js, I can't brought a necklace for you.Next time I will surely gift you.

You got it right! The power of promises in JS.Stay tuned for more articles.