Learn about Synchronous and Asynchronous in Javascript

Tram Ho

Introduce

JavaScript is a single-thread programming language, which means that only one command can be processed at a time. It is simple to write code because there is no need to worry about problems running in parallel (For example, the main thread must wait for child streams to return results to summarize).

Now imagine that the client sends the request to retrieve data from an API. It may be the case that the server may take time to process the request (Or worse, the server does not return the result) if it waits until the server returns new results, it will cause the site to feedback.

So the new Javascript creates Asynchronous to help us do this (like callbacks, Promises, async / await) to help the web flow not be blocked when waiting for a request. Cease not lengthy anymore now let us start on Synchronous and Asynchronous.

How does Synchronous Javascript work?

Now we have the following code:

Please predict how the results will print out? Yes and this is the result, let's see it:

Javascript executes the command in the order of main -> first () -> console.log ('Hi there!') -> second () -> console.log ('Hello there!') -> (Second end) – > console.log ('The End') -> (End of first) -> (End of main). With main here is the flow of the program. And for the program to run like that, the call stack is needed .

Call stack: As the name implies, the stack contains the executed commands. With the principle of LIFO (Last In First Out – Go back first, first). And since Javascript is a single-threaded language, there is only one call stack to execute the command. We can describe the process of running the above command according to the following diagram:

So that's how Javascript Synchronous does it

How does Javascript Asynchronous work?

We have the following code to illustrate Javascript Asynchronous:

Please explain. Here networkRequest uses setTimeout to simulate the action of sending a request to the API. And this is the result

To explain javascript asynchronous we need to know more about Event loop, web APIs and Message queue. I would like to note that this is not a javascript, but a part of the browser javascript compiler.

  1. Event loop : The task loop's task is to see if the call stack is empty or not. If it is empty, it will see if the message queue is waiting for a callback. If so, it will push that callback into the call stack .
  2. Message queue : Also called Task queue, Callback queue. This is the queue of tasks when using Web APIs. And the tasks will be retrieved according to FIFO rules (First In First Out – First go first) and will be event loop to bring up the call stack to execute.
  3. Web APIs : Include setTimeout, DOM Events (Example of click button, …), …

After understanding the above concepts, please explain the above code block (It will be very difficult to understand

  • First console.log('Hello World') will be included in the call stack to execute. After executing, print out the console. And push off the stack
  • Next, networkRequest() is put on the stack. And in networkRequest using setTimeout , setTimeout is put on the stack. But here the setTimeout callback needs time after 2 seconds to execute. After finishing executing, get the setTimeout and networkRequest out of the stack. After 2 seconds the callback of the setTimeout is put into the message queue (Waiting and taking out the stack is done simultaneously).
  • console.log('The End') is put on the stack to execute. And again is taken off the stack.
  • Event loop sees the stack empty, so the callback in the queue should be put on the stack to execute the code. console.log('Async Code') is executed and printed to the console. Then console.log('Async Code') is removed from the stack. So the process of running the above code is finished

It is difficult to understand, right? So see the picture below

Come here if you really understand, congratulations. If you still do not understand, please review the example in this link Click here

P / s: Can slow down speed to make it easier to observe.

ES6 Job Queue / Micro-Task queue

ES6 introduced the job queue / micro-task queue concept used by Promise. The difference between the message queue and the job queue is that the job queue has a higher priority than the message queue , which means that the jobs in the job queue / micro-task queue will be executed before the message queue .

Let's take a look at the example below:

You anticipate the test results, then see the results. And this is the result

We see that Promise is executed before setTimeout because the Promise callback stored in the job queue / micro-task queue has a higher priority than the message queue .

Next example

Result:

Conclude

We learned how to synchronous JavaScript and Asynchronous JavaScript operations and concepts such as call stack , event loop , message queue / task queue and job queue / micro-task queue . Hope this article helps you.

Share the news now

Source : viblo.asia