Developer Snippet Diary

Async await in Javascript ||Sync, Async, Callback, Promise, Aync await, Fetch Api

Sync:

Code run in sequence, Each next instruction wait to execute Next one.

Console.log("1");
Console.log("2");
Console.log("3");

Output: 

1
2
3

Async:
Execute Next instruction immediately without blockig the flow, for Async we use setTimeout function

setTimeout(hello,2000); // it will execute any given function with given time.
function hello(){
    console.log("I will be executed after 2 seconds");
}

The above code is equal to 

setTimeout(()=>{
    console.log("I will be executed after 2 seconds");
},2000);

Also this one

setTimeout(hello,2000);
const hello = ()=>{  //arrow function to a variable
    console.log("I will be executed after 2 seconds");
}

Now if we put

console.log(1);
console.log(2);
setTimeout(
    ()=>{ console.log("xd"); }
    ,4000
 );
console.log(3);

Output:
1

2

3 //don't wait for xd output, because this is async

xd //after 4 seconds

 

CallBack:
A function passed in another as argument

function calculator(a,b,DoSum){
    DoSum(a,b);
}
function sum(a,b){
    console.log(a+b);
}

So now Call calculator(1,2,sum); //inside calculator DoSum is replaced by sum and sum function is called, so we can use any parameter in place of DoSum

********* CallBack Hell *******
Let suppose we want to get a data and if returned our data then send 2nd request then 3rd then ....

we use code below 
Real case example will be (if username exist, then check password, if password and user matched then check for 2fa)

function getData(dataId, getNextData) {   // Simulate data retrieval with a 2-second delay
        setTimeout(() => {
            console.log("data", dataId);
            if (getNextData) {
                getNextData();
            }
        }, 2000);
    }
    //getData(1); // if condition is not executed, 

    // Callback hell example
getData(1, () => {   
        //getData(1, getData(2)); we can't use like this so we use arrow functions
        console.log("getting data2 ....");
        getData(2, () => {
            console.log("getting data3 ....");
            getData(3, () => {
                console.log("getting data4 ....");
                getData(4);
            });
        });
    });

************ Promise **********
    * To solve call back hell we use promise
    * Promise is promise for completion of task. It is an object
    * It has 3 states, pending, fulfilled, rejected
    * if resolve() function run promise is fulfilled, if reject function run promise is rejected else pending

Pending state

let my_promise = new Promise((resolve,reject)=>{
        console.log("promise"); 
       //in console type my_promise and check its state (its pending)
});

Resolved State:

let my_promise_resolved = new Promise((resolve,reject)=>{
        resolve(123); //resolve definition created by js internally
        console.log("my_promise_resolved"); 
        //in console type my_promise_resolved and check its state (its fulfilled)
});

Rejected Proxy

let my_promise_rejected = new Promise((resolve,reject)=>{
        reject("Error: rejected item"); //resolve is created by js internally
        console.log("my_promise_rejected"); 
        //in console type my_promise_resolved and check its state (its fulfilled)
});

    * How we use promise if we get promise from some API etc 
    * promise.then() is used when promise is fulfilled
    * promise.catch() is used when promise failed 
    * see examples below, we can use a parameter to get  PromiseResult generated by resolve or reject function

Resolved Proxy

my_promise_resolved.then(()=>{
    console.log("wao my promise is fullfiled");
});

Resolved Proxy WITH PromiseResult

my_promise_resolved.then((resu)=>{
    console.log("wao my promise is fullfiled",resu);
});

Rejected promise with PromiseResult

my_promise_resolved.catch((resu)=>{
    console.log("oh hu failed",resu);
});

************ Promise chaining ************
let suppose a async function returen promise with 4 seconds delay ie asyncFunc and we want to get someother data after getting previous one successfully we use promise.then inside promise.then

function asyncFunc(){ //think some api return you promise
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                console.log("some data");
                resolve("success");
            },4000);
        });
}
let p1 = asyncFunc(); 
    p1.then((res)=>{ //you are handling promise
        console.log("p1::: ",res);
        // geting more data using chaining so first solve p1, then p2
        let p2 = asyncFunc();
        p2.then((res)=>{
            console.log("p2::: ",res);
        });
});

We can make it simple also AND NOW compare it  with callback hell, its easy then that 

asyncFunc().then((res)=>{ 
        console.log("p1 SIMPLE CODE::: ",res);
        asyncFunc().then((res)=>{
            console.log("p2 SIMPLE CODE::: ",res);
        });
});

************  ASYNC, AWAIT ************

BUT THIS IS ALSO DIFFICULT, WE USE ASYNC, AWAIT
> async function always return a promise , no need to handle promise manually
> await, its wait untill function return promise
> but await is only used inside aync functions, ie we used below exe function

function api(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            console.log("hello");
            resolve(200);
        },2000);
    });
}
 // await api(); it is wrong
async function exe(){ //in console execute it like exe()
    await api();
    await api();
}

In callback hell, promise, promise chaining we don't need extra function , but in async await, we need to define extra function 
To prevent it we use IIFE, Immediate invoked function execution

/***** IIFE ********/
(async function(){ // no need to run exe() in console
    await api(); 
    await api();
})();

 

FETCH API: No need ajax requests anymore

Fetch api always return promise

 

const get_data = async ()=>{
    console.log("getting data");
   var responce = await fetch("https://jsonplaceholder.typicode.com/posts/1"); //return 1st response promise
   var actual_data = await responce.json(); //2ND responce
    console.log(responce); 
    console.log(actual_data); 
}

POST REQUEST:

const response = await fetch("https://example.org/post", {
  method: "POST",
  // ...
});

HEADERS:

const response = await fetch("https://example.org/post", {
  headers: {
    "Content-Type": "application/json",
  },
  // ...
});

Cancel request:

const controller = new AbortController();

const fetchButton = document.querySelector("#fetch");
fetchButton.addEventListener("click", async () => {
  try {
    console.log("Starting fetch");
    const response = await fetch("https://example.org/get", {
      signal: controller.signal,
    });
    console.log(`Response: ${response.status}`);
  } catch (e) {
    console.error(`Error: ${e}`);
  }
});

const cancelButton = document.querySelector("#cancel");
cancelButton.addEventListener("click", () => {
  controller.abort();
  console.log("Canceled fetch");
});
Posted by: R GONDAL
Email: rizikmw@gmail.com