JS Async -Await, Promises, and Callback

JS Async -Await, Promises, and Callback

Callback vs Promises and Async-Await

Callback:

A Callback is a function that is passed into another function as an argument. which means that a callback is a function executed in another function.

let's see a basic example:

function sumOfTwoNumbers(num1,num2){
   return num1+num2
}
function findCubeOfSumOfNumbers(num1,num2){ 
        let number=sumOfTwoNumbers(num1,num2)
        const cubeOfNum=Math.pow(number,3)
        return cubeOfNum ;
 }
var result = findCubeOfSumOfNumbers(2,3);
console.log(result); // 125

let's see an asynchronous example In js

alert("first")
setTimeout(()=>alert("hi"),1000)
alert("third")

 // the output of the above program is 
  first 
  third
  hi

In Javascript, when we deal with asynchronous operations like setTimeout,setInterval, etc. the callback is very useful.

let us understand it by example:

  • setTimeout/setInterval are built-in function.which takes a callback, and delay time as a parameter.
function welcomeMessage(){
 return alert("welcome user")
}

setTimeout(welcomeMessage,4000) 
  // welcome message is a callback that will appear after a 4mseconds delay.

 setInterval(()=>alert("I am appearing every 1000ms"),1000)

the primary way to handle asynchronous operations is through callbacks. but when we are dealing with more dependencies you get callback hell.

Callbackhell

callback interrupts the flow of the program if it has more dependencies. To get rid of callback hell convert the callback into a Promise.

Promises and Async-await

Promises

Promises can easily handle multi asynchronous operations which return objects in that you can attach callbacks.

function pendingMessage(){
return "please wait checking data..."
}
function successMessage(){
 return "data loaded successfully"
}
function errorMessage(){
  return "failed in loading data"
}

const getData=new Promise((pending,resolve,reject)=>{
  pendingMessage()
if(resolve){
      return resolve(successMessage())
  }else{
  reject(errorMessage())
}
})
console.log(getData)  // output: "data loaded successfully"
function getDataFromServer(callback){
         setTimeout(function(){
             callback();
       },1000)
}
function personDetails(){
console.log("PersonDetails are available to use ");
}
getDataFromServer(personDetails);  //PersonDetails are available to use

Where we have Promised, there we can use the async/await pattern.

async-await

we know that Javascript is synchronous. Sometimes we want to deal with asynchronous operations. to convert the function to asynchronous using async and await.

let a=1;
let b=async ()=>return await(alert("hi"))
let c=3
console.log(a)
console.log(b)
console.log(c)

output: 1
3
"hi"
  • callback is the primary way to handle asynchronous operations. but when it has more dependencies we encounter with callback hell.
  • to avoid it promises can easily handle multi asynchronous operations

thanks for reading the blog....