Simplified Promises in Javascript

Simplified Promises in Javascript

Promise is the most asked interview topic , in this blog we are going to discuss about the

  1. How we handle asynchronous task before promise

  2. What promises are ?

  3. How to consume promises

  4. Advantages of it

  5. Promise chaining

I assume you already know about what is callback and what problems it have while writing code in callback .

If you don’t know about callback please visit this blog for more info about it.

Basically we use callback to handle the asynchronous task(tasks which take some time to execute).

Callback open the whole world of asynchronous

Ex.

setTimeout(function (){

console.log(“sayhello”),4000}

Let find out how we work with asynchronous tasks before promise

Let’s take an example

const cart = [“apple”,”oats”,”butter”];

createOrder(cart) it will return orderId

proceedToPayment(orderId)

so here we have two api and proceedToPayment api is depent upon the createOrder, it should be executed after the order has been created .

So how can we do that , we use callback , we wrap out api proceedToPayment to a function and pass it to createOrder api

createOrder(cart,function (orderId){

 proceedToPayment(orderId)

})

So what’s the problem with this code , basically here we are depend upon the api createOrder to call the proceedToPayment api . So we are not sure how much time it takes , how many times it will call it , what if the createOrder api is written by an intern???

So here we are not sure , to make this code more efficient and trustworthy , we use Promises.

What is Promises.

Promise is basically an object which represent the eventual completion of the asynchronous task .

Let’s see how that code be improved by promises

Const promise = createOrder(cart)

Here createOrder will return a promise and and we store that in promise variable .

createOrder will return an object like {data:undefined} at starting point and then some time after the api is resolved it will be filled with data .

Promises have 3 States.

Fulfilled: This means the promise is fulfilled and you can access the result .

Rejected: This means the promise has been rejected , it will throw some error

Pending: This means that the promise is in the pending state , the processing is going on, it will be rejected or fulfilled on some time

How to consume promises

We use .then() method to consume the result .catch() method to consume the error

const promise = createOrder(cart)
  promise.then((res)=>{
  proceedToPayment(res.orderId)
}).catch((err)=>{
Console.log(err)
})

The difference between the callback and the promise is that in callback we are passing the function to it, but in promise we are attaching that function .

Let see how to create a new Promise

let promise = new Promise(function (resolve, reject) {     \
const x = "himanshu";   
const y = "himanshu" 
   if (x === y) {  
      resolve();   
 } else {   
     reject();    
} });  
promise.
then(function () {      
  console.log('Success”);
 })
.catch(function () {   
     console.log('Some error has occurred');    
});

Advantages of Promises

  • Improves Code Readability

  • Better handling of asynchronous operations

  • Better flow of control definition in asynchronous logic

  • Handle Error Better

  • Avoid Callback hell

What is Promise Chaining

when you want to handle many async operation which are depend one after another then we use promise chaining , before promises we do that by using callback hell, which is not a better way of writing code .

let's see an example

let promise = new Promise((resolve,reject)=>{
 if(true){
  resolve(100)
 }
})

promise.then((res)=> return res)
        .then((res)=> return res*2)
        .then((res)=>  return res+12)
         .then((res)=>{
         console.log(res)
           })

// output
212

So Hope you understand what promise is !

Thank you for reading this article!

If you enjoyed this article and want to learn more about Javascipt , follow me on LinkedIn at Himanshu Singh , where I post regular updates .