Asynchronous JS, why do you exist?

Asynchronous JS, why do you exist?

  • Js by default is single thread, that means everything takes place one after the another

    Task 1 --> Task 2 --> Task 3

  • So imagine if there is a function that takes a long time to finish execution, that means you are stuck until it gets over

  • If we don’t want to wait till then & we decide of executing some other function meanwhile, this is where we need Asynchronous code

  • Callback functions can help us achieve this - a function that is passed as an argument to another function to be called back later.

  • Eg: using setTimeout - its a function in js that allows me to execute a function after certain amt of time. It does so by invoking callback functions. This means we can now execute a function irrespective of the sequence

carbon.png

  • Callbacks are used extensively through js for having asynchronous code

  • There are two main types of asynchronous code style you'll come across in JavaScript code

    1. old-style callbacks
    2. newer promise-style code. More about the same we shall look in future posts
  • Thus Async code help us save waiting time & allows us to execute functions in the mean time simultaneously

We shall look upon more asynchronous codes in upcoming posts

Happy to connect with you

twitter.com/am_ruchika linkedin.com/notifications/ruchika_sood