Promises Basics, Promise.then() & Promise.catch() in Javascript

 


     Promises Basics, Promise.then() Promise.catch():

 Promises are the ideal choice for handling asynchronous operations in the simplest-      manner.

   

  • Benefits of Promises 
    1. Improves Code Readability
    2. Better handling of asynchronous operations
    3. Better flow of control definition in asynchronous logic
    4. Better Error Handling
  • A Promise has four states: 
    1. fulfilled: Action related to the promise succeeded
    2. rejected: Action related to the promise failed
    3. pending: Promise is still pending i.e. not fulfilled or rejected yet
    4. settled: Promise has been fulfilled or rejected

   ---A promise can be created using the Promise constructor. --

  Here is the syntax: 

     let promise= new Promise(function(resolve, reject){

     //do something
});
  • Parameters 
    • Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).
    • Callback function takes two arguments, resolve and reject
    • Perform operations inside the callback function and if everything went well then call resolve.
    • If desired operations do not go well then call reject.

    Promise Consumers

   Promises can be consumed by registering functions using .then and .catch methods.

   1. then() : then() is invoked when a promise is either resolved or rejected.

   Parameters: then() method takes two functions as parameters. 

   1. First function is executed if promise is resolved and a result is received.

  2. Second function is executed if promise is rejected and an error is received.

   

   Syntax:

    .then(function(result){

        //handle success
    }, function(error){
        //handle error
    })

   2. catch() : catch() is invoked when a promise is either rejected or some error has occurred in execution.

   Parameters: 

   catch() method takes one function as parameter. 

  
  1. Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
 Syntax: 
  
   .catch(function(error){
        //handle error
    })

  Here is all code:

console.log("hello console");
    //promise
    //resolve
    //reject
    //pending

    //promise constructor
    function func1() {
    return new Promise(function (resolve, reject) {
        const error = true;
        if (!error) {
        console.log("your promise is sucessfully resolve");
        resolve();
        } else {
        console.log("your promise is failed");
        reject("sorry not fulfil");
        }
        setTimeout(() => {
        console.log("your promise is return");
        resolve();
        }, 2000);
    });
    }

    func1()
    .then(function () {
        console.log("Hasan: thanks for resolving");
    })
    .catch(function () {
        console.log("failed");
    });

Comments