What is Promises in javascript ?

Promises in javascript is used to handle the asynchronus task. Promises in javascript has producing code and consuming code to handle. it means consuming code has to be wait until code can not be produce either with sucess or with error

Promises method is used to handle the promises

Syantax :

new Promise(sucessmethod,errormethod)

Promise object has two call back function. one is sucessmethod and another has errormethod.on sucess of promise sucessmethod will get call while errormethod will get call after an error in promise

Promises methods

  • promise.then()
  • promise.catch()
  • promise.finally()

then() method in promise

then() method has also two call back function one is on sucess and another is on error.similary nested then() method work


let promise=new Promise(sucessmethod,errormethod();
promise.then(sucessmethod,errormethod)


simliarly nested then() method is used to handle the next promise object created by then() method until catch() method is not called

Example



let promise=new Promise(sucessmethod,errormethod();
promise
.then(sucessmethod,errormethod) //this will handle the promise that we have created
.then() //this will handle the promise object that is created by previous then() method
.then() //simliarly a chain of than() method is called until we can't react catch() method


Syntax of catch() method:

promise1
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { console.log(value) })
.catch(err => { console.log(errr) });

Syntax of finally() method:

promise1
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { return value ; })
.then(value => { console.log(value) })
.catch(err => { console.log(errr) })
.finally();

finally method with catch method Example:


function numbercheck() {
  return new Promise((resolve, reject) => {
    if (Math.random() > 5) {
      resolve('number is greater than ');
    } else {
      reject(new Error('number is less than 5'));
    }
  });
}

numbercheck()
  .then((number) => {
    console.log(number);
  })
  .catch((err) => {
    console.error(err);
  })
  .finally(() => {
    console.log(' process done');
  });

Leave a Comment