DEV Community

Sushil Choudhari
Sushil Choudhari

Posted on

Promise in Javascript

In this blog, I will try to cover the basics of promises in javascript.
Let's talk about the idea before we get into the promise in javascript code.

A promise in javascript is just like a promise in a real life, for example, a father promises his daughter to bring chocolates while returning from the office and then the promise has to redeem either it gets completed means the father brings the chocolates or is rejected father doesn't bring the chocolates.

What is a Promise? how we can create Promise

A promise is an object which gets produced after a response to an asynchronous call in javascript code. this lets asynchronous calls work and return as synchronous values like success or failure of promise.

A Promise has a three state...

  • pending state: Initial State
  • fulfilled state: Promise completed
  • rejected state: Promise Failed

Let's create a Promise in javascript
The promise is created by the Promise function which takes a callback function having two arguments resolve and reject.

let createPromise = new Promise((resolve,reject)=>{
    // promise defination
})
Enter fullscreen mode Exit fullscreen mode

Now inside of this promise function, we need to define the actual promise so, let's take an example of a resolved promise i.e when the flag value is true the promise gets resolved and gives the message mentioned in resolve and if the value is false it gives the message mentioned in rejected.

let createdPromise = new Promise((resolve ,reject)=>{
let flag = true ;
    if(flag){
        resolve("Promise Created")
    }else{
        reject("Promise Not Created")
    }
})
 Promise Created // for flag = true
 Promise Not Created // for flag =false
Enter fullscreen mode Exit fullscreen mode

so, how to get those values and print them on the console? , we need to interact with promise therefore we use .then() anything inside in it will going to run for resolve. To get the reject value we use .catch()

let flag = true ;
    if(flag){
        resolve("Promise Created")
    }else{
        reject("Promise Not Created")
    }
}).then((message) =>{
    console.log(message) //  prints Promise Created  ( if flag=true )
}).catch((message)=>{
    console.log(message) //  prints Promise Not Created  ( if flag=false )
})
Enter fullscreen mode Exit fullscreen mode

It is similar to the callbacks but has a more organised and cleaner way.
Promises are very great to use when you need something that will take a long time to get some data from APIs and do something with data inside .then() or get an error inside .catch() if the promise is rejected.

how Promise replaces callback?
let's take an example of a callback and how it works as shown in the code

var flag = true
function getUserName(callback,errorCallback){
    if(flag){
        callback("UserName")
    }else{
        errorCallback(" failed to get UserName ")
    }
}
getUserName(  ("message")=>{
    console.log("success"+message) // print success Username (if flag = true) 
},(error)=>{
    console.log("rejected"+message) // print rejected failed to get Username (if flag = false)
} )
Enter fullscreen mode Exit fullscreen mode

let's implement this into Promise

var flag = true
function getUserName(){
    return new Promise((resovle , reject )=>{
    if(flag){
        resolve("UserName")
    }else{
        reject(" failed to get UserName ")
    }
})  
}
getUserName().then(  ("message")=>{
    console.log("success"+message) // print success Username (if flag = true) 
}).catch((error)=>{
    console.log("rejected"+message) // print rejected failed to get Username (if flag = false)
} )
Enter fullscreen mode Exit fullscreen mode

its a lot similar to callback but more readable and we can do Channing easily on a promise by using the .then() function

That's it for Promise hope you liked it

Top comments (0)