Summary of asynchronous handling in Javascript: callback, promise and async

Tram Ho

At the time of the interview, there was a question: Name the methods of handling asynchronous in javascript, I only remember each async await because I read it somewhere. But do not remember the correct syntax. So after that day I decided to learn about methods of handling asynchronous in javascript and related issues. Today I would like to write an article on this issue.

Sync with Async

Before we get into the problem, let’s find out what is synchronous and asynchronous? Synchronization: Understand simply, synchronization means performing tasks in a sequential manner, one job is completed before it can perform other tasks. For example, if there are two jobs A and B, then it means that A has done first and then turn B. So the total time for completion will be as below. This will affect user performance. Assuming a request sent to the server requires the server to perform functions such as importing files or reading or writing files, then the server will take a long time to handle these things. That also means that while the server performs that function, it will not be able to perform another action. Not to mention that while the server is doing these things, there may be many requests sent while the server has not finished, this can cause the server to crash.

Multi-thread

To overcome this situation, programming languages ​​such as C / C ++, Java, etc. will use multi-thread mechanism. This means that each time-consuming task will be performed on a separate thread without interfering with the main thread. You can still perform time-consuming tasks and still be able to capture events on the main thread.

Javascript and asynchronous mechanism

For javascript, it is a language called Single threed, you can read more single threed in the following link: https://viblo.asia/p/javascript-single-thread-lieu-da-loi-thoi- gAm5yxwkldb Ie it only has 1 thredd, so you can’t use multi thread like other languages ​​but have to use asynchronous processing mechanism With asynchronous handling, when A begins to execute, the program continues to execute B without waiting for A to finish. What you need to do here is to provide a method for the program to execute when A or B ends.

The mechanism to help you do this in JavaScript can be to use Callback, Promise or Async / await.

Callback

The callback is a piece of code that is passed as a parameter to a function and waits for a call to be executed. For example:

Ie here I expect the first action will be to print on the screen “Hello, world”, right after printing is complete continue to print the words “My name is …” We will also see the link fruit

In addition, the callback is also used when you use ajax ,. When sending the request to the server successfully and the server will respond to success, a success function will be called. Then we just need to write code to handle this callback.

Callback hell

We understand the callback already, but in the case of too many nested callbacks, it’s like when one callback is done, another can be executed, for example:

It will be unsightly if our program has dozens of such callbacks. I will be more difficult to understand and maintain. This is Callback hell and we need to avoid this when programming. There are many ways to prevent callback hell, I will talk about some common callback hell prevention methods.

Promise

Promise is a mechanism in JavaScript that helps you perform asynchronous tasks without falling into the callback hell or pyramid of doom, which is the situation of nested callback functions on too many floors. Asynchronous tasks can be sending AJAX requests, calling functions inside setTimeout, setInterval or requestAnimationFrame, or manipulating WebSocket or Worker … Here is a typical callback hell.

Promise is born to handle the outcome of a specific action, the result of each action will be success or failure and Promise will help us solve the question “If successful, what to do? If failure then what?”. Both of these questions are called a callback action.

When a Promise is initialized, it has one of three states:

  • Fulfilled Action completed and successfully processed
  • Rejected Action finished processing and failed
  • Pending Action pending or rejected

In which the two states Reject and Fulfilled we call Settled, that is, the process has been completed.

How to create a promise

Where callback is a function with 2 parameters as follows:

Where: resolve: is a callback function that handles the successful action. reject is: a callback function to handle failed action. An example to use promises to read files: In the above example, I used a nodejs module for reading the file, and the job I want to do is that after I finish reading the contents of file 1 and print out the contents of file 1, I can only see this. proceed to read the contents of the file 2. So I have to handle by passing the callback in turn in each then key function and note that in order for the back then function can be done, the callback in the then then function must be returned about a promise.

Async / await

Promise has solved quite well the callback problems. However, using promises is sometimes annoying because you must pass a callback to the then and catch functions. The code will also be a bit redundant and difficult to debug, since all the then functions are counted as one statement, so they cannot be debugged individually. And when ES7 was born, there was a feature called async / await that solved this problem

How to use asyn / await

To use the async function, we need to declare the async keyword immediately before the function definition keyword. That is, with the function defined with the function keyword, we must declare immediately before the function, with the arrow function (arrow function) we must declare the input parameter set before. With this async keyword, we can wait for the Promises (asynchronous operations) to process in that function without temporarily using the main thread with the await keyword as in the above example.

The result of the async function is always a Promise regardless of whether you call await – whether or not to handle asynchronously. This promotion will be in a successful state with the result returned with the async keyword return, or the failed state with the result being pushed through the throw keyword in the async function. Thus, we can see the nature of the async function is Promise.

With Promise, we can handle exceptions with fairly simple catch. However, it is not easy to follow and read. But with the async function, this is extremely simple with the try catch keyword exactly as the sync operation.

Summary

In summary, I would like to summarize a few main ideas related to async / await as follows:

  • await is always in the async function as in the above example (await cannot be in a function without the declaration of the preceding async keyword)
  • The order of executing the statements in js in general or nodejs in particular is run from top to bottom (ie, run sync rather than async), except for functions related to I / O to run async. more in the event loop article in js)
  • When you meet await, it will convert that function into a promise, with the callback being all the code behind that await. The await nature is a promise, the code behind await is actually the code inside the callback of that await function.
Share the news now

Source : Viblo