Wednesday, December 27, 2017

JavaScript : Callback and Promise

Callback

1. JavaScript statements execute line by line without waiting for previous async statements to finish.
2. Callback place vital role to execute required code after async code completes.
3. Callback is a function that is passed to another function as a parameter, and Callback function gets called inside the another function

different ways to call Callback functions

1. Passing anonymous function as callback function

$("#btnhome").click(function() {
  alert("Home Clicked");
});

Here, click method expecting function as parameter. So, anonymous function passing as a parameter

2.  Passing named function as callback function

function displayalert(){
alert("Home Clicked");
}
$("#btnhome").click(displayalert);

Here, click method expecting function as parameter. So, named function passing as a parameter

var displaymessage=function()
{
alert("message display");
}
var showAlert=function(callback)
{
console.log("showing alert message");
callback();
}

// calling function
showAlert(displaymessage);

3. Callback function with parameters

var add=function(a,b)
{
return a+b;
}
var calculate=(num1,num2,callback)
{
Console.log("adding numbers");
var result=callback(num1,num2);
Console.log(result);
}

// calling function
calculate(2,5,add);

Promise

1. Promise are next version of Callbacks
2. It avoids nesting Callback and multiple try/catch
3. It represent asynchronous operations as a sequence
4. It is a different syntax for achieving the same effect as callbacks. The advantage is increased readability
5. A promise represents the result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize
6. A promise contain callback function two arguments, resolve and reject , which are both functions. All your asynchronous code goes inside that callback. If everything is successful, the promise is fulfilled by calling resolve() . In case of an error, reject() is called with an Error object. This indicates that the promise is rejected

Example:
var p= new Promise(function(resolve, reject) {
  if (true) {
    resolve("successfull");
  }
  else {
    reject(Error("failed"));
  }
});

// calling Promise
p.then(function(response) {
  console.log("Success!", response);
}).catch(function(error) {
  console.log("Failed!", error);
})

Promise Chaining : It is used to call multiple async operations one after another

asyncThing1().then(function() {
  return asyncThing2();
}).then(function() {
  return asyncThing3();
}).catch(function(err) {
  console.log('error occured',err);
})

Callback with Nesting

api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
        });
    });
});
     
Promise with Nesting

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});
        
Happy Coding :)