What is Promise, why do we need it?

What is Promise, why do we need it?

·

2 min read

HEY Gorgeous people on internet today let's learn about the Promise which is majorly used for async programming in JavaScript. First let us know what is the need to use Promise's when we have MIGHTY Callback🤴.

Need For Promise:

As we know that callbacks are awesome for async programing and they were are stepping stone for async programming in JavaScript because they give us the ability to call the function later when ever it is required. But it comes with certain problems that we face like.

  1. Callback Hell
  2. Inversion of Control: we are not sure when our callback function would be called.

These are some of the problems we face while using the callback. So here comes the PROMISE for rescue.

Promise: It is an object representing eventually completion or failure of a asynchronous operation.

Let's code some code😉 to differentiate.

Here is Callback Code:

function hello1(resolve,reject){
   var a=10;
     if(a===0){
      resolve("Hey People")
    }else{
      reject("Sorry boy")
    } 
}
hello1((msg)=>{
  console.log(msg);
},(err)=>{
  console.log(err);
})

This looks fine as it is small code but when try starting passing more functions to the result that you obtained it becomes a BIG MESS 🥵.

Like this: https://images.app.goo.gl/TRnqB2wSSvfxMLCC8

sq.png

This is how Promise code look's like 😎:

function hello(){
  var a=10;
  return new Promise(function(resolve,reject){
    if(a===0){
      resolve("Hey People")
    }else{
      reject("Sorry boy")
    }
  })
}

hello().then((res)=>{
  console.log(res);

}).catch((er)=>{
  console.log(er)
})

when you use promise's your code looks more cleaner and further results of first then block can be sent next then block.

Thanks for going through the article please feel free to like and comment and share any extra points that i have missed.

Arigatō GUYS

Did you find this article valuable?

Support SYED IMAM by becoming a sponsor. Any amount is appreciated!