Hello. This lesson we talk about the Asynchronous Programming in JavaScript, I hope this lesson is useful for you.

They say time is the 4th dimension in our universe. I say that asynchronous programming is the 4th dimension of your logic. You wanna elevate your coding to this new level of mastery?

Asynchronous vs synchronous

// 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 about timeouts, event listeners, ajax
  • // requests, promises, fetch, callbacks, database
  • // interaction, filesystem interaction?
  • // Those are executed asynchronously, which means
  • // that we need to give the request and wait for
  • // the response from the other side.

Asynchronous programming

// The simplest example:

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

// you would expect 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 reponse.. That’s why it
  • // first executes all synchronous tasks and
  • // after that those which are asynchronous (like timeouts/requests).

real-life example

// If we try to do the following process synchronously, it won’t work:

let response = fetch('myImage.png');
let blob = response.blob();
  • // Why? Becacuse 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 in play:
fetch('muImage.png').then(response) => {
   // What you put here, runs after the data 
   // is fetched. You receive 'response' and 
   // you can use it. (display in dom or etc)

The Source: https://www.instagram.com/webmaster_project/