Asychronization In Js
On my journey as a self-taught developer
i would love to share what I learned yesterday about asynchronous javascript. in, javascript there are two types of executions which are synchronous and asynchronous. okay, what do I mean by that and what do these mean. well, start from the first which is the synchronous execution in js.
Let's take the above few lines of code as an example of our study.
Imagine you're baking a cake. You start by mixing the batter (let's call this "Task A"). While the batter is resting, you can clean up the kitchen (Task B). This is an example of asynchronous execution. You're doing multiple things simultaneously without waiting for one to finish before starting another.
Now, imagine you're making a sandwich. You need to get the bread, then the cheese, and then the tomato. You can't get the cheese until you have the bread, and you can't finish the sandwich until you have the tomato. This is a synchronous execution. You're doing one thing at a time, in a specific order.
In JavaScript, asynchronous and synchronous execution work similarly.
Synchronous Execution:
Code is executed line by line, one after the other.
If a task takes time (like fetching data from a server), the script pauses until the task is complete.
Asynchronous Execution:
Code can execute tasks in parallel.
If a task takes time, the script doesn't pause. It moves on to the next task and comes back to the long-running task when it's finished.
In the given code snippet:
Line 7-9: The
fetch
function is used to make an asynchronous request to the REST Countries API. This means the script doesn't wait for the response; it continues to the next line.Line 10-34: The
addEventListener
function is used to set up a callback function that will be executed when the response is received. This is an example of asynchronous programming.
So, even though the code seems to be executed line by line, the actual execution is asynchronous. The script continues to run while waiting for the API response, making it more efficient and responsive.
In summary, what I actually learned today is :
Synchronous execution is like following a recipe step-by-step.
Asynchronous execution is like multitasking, doing multiple things at once.
JavaScript uses asynchronous programming to make web pages more responsive and efficient.
Let me share with you a repository link that contains lot of useful APIs