DEV Community

Cover image for Promises
E.Tulasi Ram
E.Tulasi Ram

Posted on • Edited on

Promises

Why Promises required?

  • Callbacks is a great way when we are dealing with basic cases like minimal asynchronous operations.But when we are developing a web application that has lots of code, then working with Callback will be messy. This excessive Callback nesting is often referred to as Callback hell.

  • To deal with such case we use promises instead of Callbacks.

How does promises work ?

  • Promises is an object which represents the eventual completion or failure of an asynchronus operation and return a single value
    based on the operation being rejected or resolved.

  • It has three states

  1. Pending

2.Fulfilled

3.Rejected

  • Pending:It is the initial state of each Promise. It represents that the result has not been computed yet.

  • Fulfilled:It means that the operation has completed.

  • Rejected:It represents a failure that occurs during computation.

Creating a promise

  • In JavaScript, we can create a Promise by using the Promise() constructor.

  • syntax

const promise = new Promise((resolve,reject)=>{...});
Enter fullscreen mode Exit fullscreen mode

Example

 let Promise = new Promise((resolve, reject)=>{  
    let a = 3;  
    if(a==3){  
        resolve('Success');  
    }  
    else{  
        reject('Failed');  
    }  
}); 
Promise.then((message)=>{  
    console.log(message)  
}).catch((message)=>{  
console.log(message)  
})  
Enter fullscreen mode Exit fullscreen mode

Output
Success

Promise methods

The Promise methods are used to handle the rejection or resolution of the Promise object.

.then()

  • This method invokes when a Promise is either fulfilled or rejected. This method can be chained for handling the rejection or fulfillment of the Promise. It takes two functional arguments for resolved and rejected.

Example

let success = (a) => {  
    console.log(a + " it worked!")  
  }  

  let error = (a) => {  
    console.log(a + " it failed!")  
  }  

  const Promise = num => {  
    return new Promise((resolve,reject) => {  
      if((num%2)==0){  
        resolve("Success!")  
      }  
      reject("Failure!")  
    })  
  }  

  Promise(100).then(success, error)   
  Promise(21).then(success,error)  
Enter fullscreen mode Exit fullscreen mode

output
Success! it worked!
Failure! it failed!

.Catch()

  • It is a great way to handle failures and rejections. It takes only one functional argument for handling the errors.

Example

const Promise = num => {  
    return new Promise((resolve,reject) => {  
      if(num > 0){  
        resolve("Success!")  
      }  
      reject("Failure!")  
    })  
  }  

  Promise(20).then(res => {  
    throw new Error();  
    console.log(res + " success!")  
  }).catch(error => {  
    console.log(error + " oh no, it failed!")  
  })  
Enter fullscreen mode Exit fullscreen mode

OutPut
Error oh no, it failed!

Top comments (0)