Shamaayil Ahmed

Shamaayil Ahmed

Asynchronous JavaScript

Asynchronous JavaScript

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

This is an intro to asynchronous concept in JavaScript , serves the starting point for all fluid websites that we come across.

Asynchronous?

IMG_20200829_230806.png

Actually javascript is synchronous or single-threaded i.e, at a moment of time a single piece of code is only processed. So that makes JS incompactible is majority of the situations;

Take this situation where we have to display a sign in notification while starting a site we go ahead or close the notification until by now the site is not yet loaded as of synchronous javascript in action cos only one action at the moment.

This can be overwhelming as of the technology spike , we have got dual core to Octa core processors ; So this silly situation doesn't make any sense and is waste of computing power.

So this is where asynchronous JS come into action of implemention multi-threaded actions without freezing the UI.

JavaScript solves the situation using Callbacks - functions which are called when the process completes

Throughout the solutions : The scenario is to navigate through a link to get the data in thyself.

Callbacks

Unknowingly we have come across callbacks in JS, Lets make it more clear in the code snippet;

addEventListener('click',changeColor)

here changeColor() is nothing but a callback function which is only called when a click event is captured.

We declare some actions asynchronous due to the time consumption of thyself, So in order to some asynchronous actions we use, setTimeout(),setInterval() or requestAnimationFrame() which probably take time or repeats after certain time.

scenario explained

   function navigateLink(IP,cache,callback){
    setTimeout(()=>{
        console.log('Navigating...');
        callback( {userIP:IP});
    },1000);             //takes 1ms to process
   }

  function displayData(cache,callback){
    setTimeout(()=>{
        callback( ['Lorem ipsum' ,'img.png' ,'vid.mp4']);
    },2000);            //takes 2ms to process
  }

  const user=navigateLink(12.222.023.456,"browser.cache",(user)=>{
    console.log(user);
    displayData(user.cache,(data)=>{
        console.log(data);
    })
  });

OUTPUT:
   Navigating...
   { userIP: '12.222.023.456' }
   [ 'Lorem ipsum', 'img.png', 'vid.mp4' ]

So that's the simplest way of declaring actions asynchronous , But when there are many action to be done callbacks become a LoopHell or pyramidOfDoom, the code becomes nasty.

ES6 introduced promises which makes these process easy.

Promises

That's more self explanatory, we make a promise that takes time either we fulfill it or we miss it. Thats what these promises in JS do takes in resolve and reject when promise is resolved would call a (then) to do more actions or catch when promise is rejected.

scenario explained

   function navigateLink(IP,cache){

    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
        console.log('Navigating...');
        resolve( {userIP:IP});
     },1000);
     })    
    }

   function displayData(cache){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
        resolve( ['Lorem ipsum' ,'img.png' ,'vid.mp4']);
    },2000);
    })
   }

  navigateLink('12.222.023.456',"browser.cache")
    .then(user=>displayData(user.cache))
    .then(data=>console.log(data))

OUTPUT:
   Navigating...
   [ 'Lorem ipsum', 'img.png', 'vid.mp4' ]

For dealing with two or more promises we have Promise.all(),Promise.allSelected(),Promise.race()

These promises are the basics of all Web API's,Node.js,reactJS Though promises can be confusing as well complicated that's were, ES8 synchronous style Async and Await.

Async ,Await

These are more of a keywords to implement asynchronous actions more conveniently than ever.

scenario explained

   function navigateLink(IP,cache){

    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
        console.log('Navigating...');
        resolve( {userIP:IP});
      },1000);
     })    
    }

  function displayData(cache){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
        resolve( ['Lorem ipsum' ,'img.png' ,'vid.mp4']);
    },2000);
    })
   }

  async function display(){
    try{
      const user= await navigateLink('',"");
      const data=await displayData(user);
      console.log(data);
     }
     catch(err){
         console.log('ERROR');
     }
   }  

  display();

OUTPUT:
  Navigating...
  [ 'Lorem ipsum', 'img.png', 'vid.mp4' ]

So that's the easiest of all the above.

Concluding

Asynchronous actions or process are of atmost important these days for the UI as well the performance of server.

hope you all got some thing to grind-in from here :)

 
Share this