Asynchronous handling story in JavaScript (Part 1)

Tram Ho

JavaScript is a single-thread language, meaning it only runs on a single thread. If you handle synchronous mechanism, then when you perform tasks such as manipulating the database, calling requests to the server … then the application will have to spend quite a long time waiting for the jobs. The above is done and then started to do the next job, which will consume a significant amount of time, affecting user experience or in the bad case, can lead to … hanging. application.

Asynchronous handling is a complex and inevitable task. Therefore, we should take a little time to learn about it, specifically here I introduce through the asynchronous handling in JavaScript with three tools callback , promise and async / await .

Let’s start!

I. Synchronous and asynchronous

1. Synchronous processing (Synchronous / Sync)

As the name implies, when processing synchronously, the program will run step by step and only when step 1 is completed, will begin to move on to step 2. One of the basic principles in preparation The process of applying this rule is compilation . When compiling, the compiler will translate in turn from left to right, from top to bottom, when finished translating the top line, then translating to the bottom line, this will generate a state called standby state .

Example of the following code:

The program will run sequentially from the first line to the last line. Start with initialize a, b, c then calculate kq1 first and then calculate kq2 and finish.

Taking a practical example of cooking, you will first cook rice, wait for cooked rice before turning out fried eggs, cooked eggs, then turn to soup and finally eat rice.

Good side :

  • Because running in accordance with the rules, it will limit making errors related to the process.
  • If it is faulty, it will be easy to find and fix, easy to manage.

The bad side :

  • Because they run in sequence and have to wait for each other, they will generate a waiting state , there will be commands that need to manipulate external data so it takes a while to retrieve data before processing. take time, affect user experience.

2. Handling asynchronously (Asynchronous / Async)

In contrast to Synchronous, Asynchronous allows the program to jump certain steps to execute certain pieces of code. If the second job finishes first, it may produce results before the first job.

Let’s take another example of cooking: instead of waiting for cooked rice to fry eggs, cook the rice and set the time (callback) and then turn to fry the eggs.

Good side :

  • With asynchronous work, multiple tasks can be performed at the same time without waiting for each other, minimizing processing time because of the reduced waiting time for a task to complete.

The bad side :

  • Hard to control
  • One more data manipulation must go through two steps: validate the data and add data, if the validate operation occurs after the additional operation, then nothing is worse.

II. Callback (ES5)

1. Concepts

Callback is the first solution offered by Javascript to solve problems related to asynchronous handling in the desired order.

Definition of callback according to MDN web docs page:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Basically, the callback is to pass a piece of code ( function A ) into another piece of code ( function B ) as an argument. At some point, function A will be called by function B (callback).

After reading the above, you do not understand what is a callback? I first learned about it too, to make it easier to understand, I would like to take an example below.

2. Examples and how it works

Take the example of my cat, normally it will take 5 seconds to drink water before eating.

Try the example above, you will see that the cat eats his rice first even though he hasn’t finished his drink yet. To make sure the cat eats and drinks in the correct order, we will need information when the cat is finished drinking water before feeding the cat. To do so we add a lotus next to the cat to make sure the cat finishes drinking water before giving the rice tray.

Or you can simply write it down to

3. Pros / cons of callback

Advantages :

  • Callback is a fairly common model so very easy to understand
  • It is very easy to implement in our functions

Cons :

Basically, the callback can solve the problem of handling asynchronous in javascript, but when put into practice it has quite a lot of problems such as:

  • When working asynchronously, the callbacks have to wait for each other to execute, resulting in a longer time to complete the job.
  • Verbose, difficult to read, difficult to maintain.
  • Callback hell (pyramid of doom): is the suboptimal code which leads to having too many nested callbacks which will take time for maintenance and bug fix. Rough callback hell looks like the picture below.

To avoid such a callback hell situation, there are many ways such as designing the application in the form of a module, naming the callback, defining the function before calling … details refer here .

Conclude

The article is quite long so I would like to divide it into 2 parts. In the next section, I will discuss about Promise, Async / await and its advantages and disadvantages.

Thank you for reading to the end of the article.

Share the news now

Source : Viblo