Asynchronous Programming in JavaScript

Asynchronous Programming in JavaScript

·

2 min read

They say time is the fourth measurement in our universe. I say that nonconcurrent(asynchronous) computer programs are the fourth element of your rationale. You wanna raise your coding to this new even out of authority? Let's read this post.


First, let's understand the opposite, What is synchronous? It is simply executing code by the order in which it was declared.

console.log('a') // logging 'a'
console.log('b') // logging 'b'
console.log('c') // logging 'c'

But what's about timeouts, event listeners, ajax requests, promises, fetch, callbacks, database interaction, filesystem interaction?

Those are executed asynchronously, which means we need to give the request and wait for the response from the other side. The simplest Example:

setTimeout(() => {console.log(5)}, 0); 
console.log(10); 
console.log(15); 

// you would exepct logged:  5, 10, 15
// what gets logged:  10, 15, 5

The parser won't stop and wait for the asynchronous process to finish, even if it has 0ms delay - it is still asynchronous and it may never get a response... That's why it first executed all asynchronous tasks and after that those which are asynchronous. (Like timeouts/requests).

Example: If we try to do the following process synchronously, it won't work:

let response = fetch('image.png'); 
let blob = response.blob();

Why? Because on the second line, we try to access the response before we even got it from the fetch(). We need to first wait for the response and then use it. That's where asynchronous comes into play:

fetch('image.png').then((response) => {
    // what you here, runs after the data is fetched. you receive 'response' and you can use it. (display in DOM, etc)
});

Thanks for Reading.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!