Asynchronous Javascript

Lokesh RevanuruLokesh Revanuru
3 min read

1.What is Callback in javascript

  • A Function that can be passed in a parameter in another function is called callback function
function myvalue(val){
console.log("This is myval function");
}
function callback(){
console.log("This is callback function");
}
myvalue(callback);

uses of Callbacks

  1. handle the Asynchronous operations

  2. Making network requests

  3. reading files (or) setting timers

Why Callbacks..?

  1. To implement the Asynchronous behavior

  2. They enable non-blocking code execution and improving performance.

  3. Callbacks are essential for handling events like user inputs or API responses.

What is callback hell…?

Nested callbacks are become deeply interlinked and difficult to manage , Then code is hard to read and understand.

The below code Structure of callback hell is Pyramid of Doom.

 function getcheese(callback){
    setTimeout(()=>{
        const chesse= "cheese";
        console.log("this is food item of:-", chesse);
        callback(chesse);
    },2000);
 }
getcheese((cheese) =>{
    console.log("got the", cheese);
});


function makedough(cheese, callback){
    setTimeout(()=>{
        const dough = cheese + "dough";
        console.log("this is dough", dough);
        callback(dough);
    },2000)
}

function bakepizza(dough, callback){
    setTimeout(()=>{
        const pizza = dough + "pizza";
        console.log("here my pizza", pizza);
        callback(pizza);
    },2000);    
}


/// This is callback hell 
getcheese((cheese)=>{
   makedough(cheese, (dough)=>{
        bakepizza(dough, (pizza)=>{
            console.log("make my pizza", pizza);
        })
   })
})

//This structure of callback hell is Piramid of Doom.

Why do we need better solution than callbacks..?

  1. The callback hell.

  2. Error handling.

  3. Readability and Maintainability.

  4. Flow control.

  5. Pyramid of Doom.

Promise:

Promise Definition

Promise is a object representing the eventual completion or failure of Asynchronous operations. And Promises are immutable in nature. they have containing Three stages

  1. Pending:-

  2. Fullfilled:-

  3. Rejected:-

How to create a new Promise

we can create a promise by using new keyword.

let firstPromise = new Promise((resolve, reject) =>{
        // do something
)};
  1. Here promise is a constructor() it takes function as a argument and also take two parameters resolve and reject.

  2. Promise return Successfully ————————→ Resolve

  3. Promise return Failed ———————————→ Reject

What is promise chaining

Definition

It’s a pattern to ensure the execution in a specific manner.

createOrder((cart)
    .then((function(orderId){
        return procedetoPayment(orderId);
    })
    .then((function(paymentInfo){
        return showorderSummery(paymentInfo);
    })
    .then((function(paymentInfo){
        return updatewalletBalance(paymentInfo);
    })
});

Error handling in Promises

Error handling in promises is done using the .catch() method or by passing error-handling logic directly into the .then() method.

doSomething()
  .then(result => {
    return doSomethingElse(result); 
  })
  .then(finalResult => {
    console.log(finalResult);
  })
  .catch(error => {
    console.error("Error caught:", error);
  });

What are the methods in Promises

1. Promise.all()

Promise.all([p1, p2,p3])
p1 -> 3sec
p2 -> 2sec
p3 -> 1sec
After 3sec [ val1 , val2, val3]
 wait for all of them to finish 4
if any API is failed
Promise.all([p1, p2,p3])
immediatly as soon as happen -> errorwill get after 1 sec
and it will not wait  for any promises.

2. Promise.allSettled()

Promise.all([p1, p2,p3])
 p1 -> 3sec
 p2 -> 1sec
 p3 -> 2sec
 wait for all promises to sattled after 3 sec
[val1, val2, val3]
it will show the error messsage.

3.Promise.race()

Promise.all([p1, p2,p3])
 p1 -> 3sec
 p2 -> 5sec
 p3 -> 2sec

after 2sec 
output:-
    [val3]
The value of the first sattled promise we will get.

4.Promise.any()

Promise.all([p1, p2,p3])
p1 -> 3sec
p2 -> 1sec
p3 -> 2sec

wait for the first sucessfull promise.
    output:-
    [val1]

seeking for first secess.

Async and await

what is Async / await…?

Async:- it is a keyword before put the function then it is a async function . it is always returns to a promise.

await:- await is a keyword, that can only used in a inside a async function. and write before the promise and resolve the promise.

const p1 = new Promsie((resolve, reject) =>{
    resolve("Promise resolved value!");
   });
async function getData(){
    return p1;
}

async fucntion handlePromsie(){
    const val = await p1;
    console.log(val);
    }
handlePromise();
0
Subscribe to my newsletter

Read articles from Lokesh Revanuru directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lokesh Revanuru
Lokesh Revanuru