DEV Community

Yaswanth K N
Yaswanth K N

Posted on

Asynchronous JavaScript

  • Asynchronous code can make a program run parellely without blocking,while performing a big task that takes in more time to complete.
  • For Example: readFiles in JS are asynchronous meaning, JS will not wait for readFile() to complete it's operations
  • So, Generally to handle these asynchronous operations we use callbacks, Promises, async and await.

CallBacks

  • These are the functions that we pass as a reference to another function which will call this callback function somewhere in it's exicution.
  • Callback functions generally used while handling asynchronous operations with some if conditions

Example:


function callback(){
    console.log("I am a callback function called after 2 seconds");
}
function asynchronous_fun(callback){

    setTimeout(()=>{
        callback();
    },2000);

}

asynchronous_fun(callback);
// Outout will be printed after two seconds
Enter fullscreen mode Exit fullscreen mode
  • In the above example, we have used setTimeout() which is a async function and will call the callback function after two seconds.
  • That's why it is printing after 2 seconds
  • In the above operation javascript engine will not wait till setTimeout() function exicute callback function.
  • So, we used callback technique to ensure our callback function exicuted after 2 seconds
  • Callbacks can be used to control the order of operations that we perform in a async code

example:


function  f1(){
    setTimeout(()=>{
        console.log("f1");
        f2(f3);
    },1000);
}

function  f2(){
    setTimeout(()=>{
        console.log("f2");
        f3();
    },3000);
}

function  f3(){
    setTimeout(()=>{
        console.log("f3")
    },2000);
}
f1(); // f1 f2 f3
Enter fullscreen mode Exit fullscreen mode
  • In the above example, we have used callbacks for sequence exicution, otherwise it would have been a random exicution.

Promises

  • Promise is a object in JavaScript which is useful in maintaining a better code control than a callback
  • Promise will have three states
    • pending : while the exicution is going on
    • fullfilled : when exicution is successfully completed
    • rejected : some error has occured during exicution
  • we generally use promise to handle asynchronous code in javascript
  • Promise object will have two functions
    • .then(): It will have data from the object if promise is fullfilled
    • .catch(): It will have error object if promise is rejected

Example:

//Promise object
const promise = new Promise((resolve,reject)=>{
    // Do operations here
    const result = "Hi, I am a promise returning successfuly"
    let error = false;
    if(!error){
        resolve(result);
    }else {
        reject("Some error has occured while fullfilling promise")
    }
});

//Collecting result from promise

promise().then((response)=>{
    console.log(response); // This will print the result message
}).catch((error_message)=>{
    console.log(error_message); //This will print message that was passed to reject function incase of rejection in promise
});

Enter fullscreen mode Exit fullscreen mode
  • We can use promise chaining to have sequnetial exicution of asynchronous operations
  • This is more cleaner way of writing code instead of using callbacks.

Code Control

  • It is the process of making the asynchronous code exicute in a required sequence
  • This can be achieved with various techniques like callbacks, Promises async and await as i said earlier

  • Let's take the same example of callbacks and how we achieved code control

  • we have three functions which have differenet exicution times. so, If we remove callbacks in the code and we run it output will be as shown

example:


    function  f1(){
        setTimeout(()=>{
            console.log("f1");
            //f2(f3);
        },1000);
    }

    function  f2(){
        setTimeout(()=>{
            console.log("f2");
            //f3();
        },3000);
    }

    function  f3(){
        setTimeout(()=>{
            console.log("f3")
        },2000);
    }

    f1();
    f2();
    f3();

//Output : f1 f3 f2
Enter fullscreen mode Exit fullscreen mode
  • So, as we can see the output is not in our control or it's not working as per our requirement
  • So, to make it work uncomment the callback functions and run only f1() function, you will see that the output is in the order ( f1 f2 f3 ).
  • This is called code control
  • we have achieved this using callback functions
  • we can also use Promises, async and await to achieve code control

References

Top comments (0)