Callback Function and Promises

    About Callback Function and Promises in  JavaScript Explained

    What is Callback Function?

    A callback is a type of function that is passed into another function as an argument and the the function is invoked inside the outer function to complete the some kinds of tasks or action.

    Let's see quick example here:

    
    function greet(name) {
      alert(`Hi, ${name}`);
    }
    
    function inputName(callback) {
      const name = prompt("Please enter your name.");
      callback(name);
    }
    
    inputName(greet);
    
    This above code is a synchronous callback as it is executed immediately. However the callbacks are often used to continue code execution after an asynchronous operation.

    Let' See another example:

      
    function calculate(num1, num2, callbackFunction) {
        return callbackFunction(num1, num2);
    }
    
    function calcProduct(num1, num2) {
        return num1 * num2;
    }
    
    function calcSum(num1, num2) {
        return num1 + num2;
    }
    alert(calculate(5, 15, calcProduct));
    alert(calculate(5, 15, calcSum));
    
      
    
    Firstly we defined three functions and then we passed callbackFunction in calculate function and we used it as callback function. then we used calcProduct and calcSum function as arguments when calling calculate function at the bottom of code.

    What is Promises ?

    A Promise is a proxy for a value not necessarily known when the promise is created. It is also an object that represents the eventual completion or failure of an asynchronous operation and its resulting value.

    A Promise is in one of these states:
    -pending : initial state, neither fulfilled or rejected
    -fulfilled: the operation is completed successfully
    -rejected: the operation failed

    Let' See example:

    let promise=new Promise((resolve,reject)=>{
    let a=1+2
    if(a===3){
    resolve("Success")
    }
    else{
    reject("failed")
    }
    })
    
    promise.then((msg)=>{
    console.log(msg)
    }).catch((msg)=>{
    console.log(msg)
    })
    
    //this code prints "Success" message
    
    

    Let' See another example:

    let promise=new Promise((resolve,reject)=>{
    let a=1+1
    if(a===3){
    resolve("Success")
    }
    else{
    reject("Failed")
    }
    })
    
    promise.then((msg)=>{
    console.log(msg)
    }).catch((msg)=>{
    console.log(msg)
    })
    
    //this code prints "Failed" message
    
    
    

    0 Comments