Photo by Thorsten Konersmann on Unsplash
We compare you and JavaScript.
What’s this insanity, dude?, you ask. Fret not, I’ll tell you why.
Can you type on more than one finger? Can you do the dishes and listen to your favourite song on your phone? Can you speak to your classmate and pretend to write on your note so that teach doesn’t catch you pretending?
If yes, you’re multi-threaded. You can handle multiple actions at the same time. And like you found out now, a thread would mean a set of instructions executed one after the another.
Unlike you, a human being, poor JavaScript is single-threaded. It can’t run two or more scripts in the same time - they’ve to be done one after the other.
Consider the following program :
function display(array)
{
for (i in array)
{
return array[i];
}
}
let spotifySongs = ["Winter of Our Youth", "The Nights", "Glory", "Pompeii", "Shame"];
let displayMySongs = display(spotifySongs);
console.log(displayMySongs);
Here, the program has to wait for the for-in
loop to finish looping. This could prove costly if it were a giant program with many different functions.
To solve this huge problem, here comes asynchronous programming.
Asynchronous programming
Asynchronous programming is a technique where a program starts a task that may run for a long time, and still responds to other events while it runs. Once the big task is done, the program presents the result to you.
So the program doesn’t wait like a sitting duck for a stupidly long thread to complete, but instead does all the other chores to be done.
Some example of ‘stupidly long’ threads [which are essential, mind you] are : Making HTTP requests using fetch()
, Asking a user to select files from their file explorer using showOpenFilePicker()
, etc.
Callbacks
Callbacks are functions passed as arguments to another function.
For example, let’s say we’ve an array of 20 random numbers :
let arr = [];
for (let i=0; i<=20; i++)
arr.push(Math.floor(Math.random() * 20));
We wish to get the odd and even numbers of this array :
function getEven(array)
{
let final = []
for (i in array)
{
if (array[i]%2==0)
final.push(array[i]);
}
return final;
}
function getOdd(array)
{
let final = []
for (i in array)
{
if (array[i]%2!=0)
final.push(array[i]);
}
return final;
}
console.log(getEven(array) + getOdd(array));
//10,16,14,4,4,10,4,14,6,0,16,16,14,01,19,1,3,15,1,19
The output looks nasty, alright? What happened to ‘waiting patiently for another function’?
This happens because these functions are asynchronous! They just happen simultaneously. Let’s make them two console outputs and check them.