Hi All,
I would like to take this opportunity and explain you the asynchronous programming in JavaScript.
Before diving deep into asynchronous concepts like callbacks, promises, async/await.
Javascript is a synchronous single threaded programming language – JavaScript (JS) Engine will execute one task at a time.
JavaScript is also a interpreted programming language – JS Engine executes the code line by line from top to bottom.
So, based on above two sentences we cannot run different task in parallel. Isn’t it? Is it good or bad? If you take other languages like Java or .net we have something called multi threading.
No friends, even in JavaScript we can achieve asynchronous behaviour with the help of callbacks and promises.
callbacks – in simple terms : calling back whenever time comes.
Similarly in JavaScript, if a function “A” gets called by function “B”, somehow we must give the function “A” control to a function “B”.
How to achieve it in JS?
Pass function A as an argument to the function B and function B will take care of function A. That’s all you have to do! ๐
Sample Code Example:
function A(){ console.log("Function A called!") } function B(funcA){ console.log("Inside Function B") funcA() // function A gets called here! } //calling or invoking function B B(A)
In the above code, we have given complete control of function A to function B.
We will go to next level to understand asynchronous with the help of callbacks. I would strongly say that, in JavaScript asynchronous behaviour exist only because of callbacks!!!
console.log("Start") setTimeout(function (){ console.log("setTimeout Called!"), 5000 } console.log("End")
setTimeout is one of the web APIs in JavaScript which takes two arguments 1. callback function and 2. Delay time
When JS engine starts, it goes line by line. So,
First it ogs “Start” in the console.
Then it registers a setTimeout web API in the browser and continues to execute next statements.
Then it logs “End” in the console.
Finally, JS engine waits for the timer (5 sec) to expire then it execute the callback function to log “setTimeout Called!”
This is how we can achieve asynchronous programming in JavaScript.
Continue to this… I will come up with promises and async/await concepts. Stay tuned!
Keep learning and keep sharing ๐
Cheers,
Adarsha ๐