3 ways to handle asynchronous JavaScript

Tram Ho

Javascript is single-threaded, which means it can only process one statement at a time. To remove this barrier, we can use asynchronous, and this article I will guide and give the basics of 3 ways to write asynchronous code in JavaScript.

What is asynchronous in JavaScript?

JavaScript is essentially a single threaded language, and it runs on a single thread. This thread is based on a concept called the event loop . This thread will respond to events as they occur. As a single-threaded language, JavaScript can only process one statement at a time. While processing that statement, the thread will be blocked.

This streamlined simplicity has many advantages, the simplest of which will make the code easier. You won’t need to worry about concurrency . Your code will be executed from top to bottom according to the way you code. You also won’t have to worry about having many different things running at the same time.

However, it still has the big disadvantage of having only one job done at a time. Everything else has to wait until it completes before it can be executed. This is a real problem if you have to get data from an API.

When calling the API synchronously / synchronously, this may block the main thread until processing is complete. So your code will have to wait until the main thread is open, which means your app will freeze and become unresponsive.

The example above will have problems as soon as there is a delay in the API call. In that case our code will run in a different order than you’d expect. That could lead to unnecessary problems.

The solution to the problem is to write asynchronous code, put the API call into asynchronous handling. By doing so, JavaScript can run many different tasks and run at the same time. When running an asynchronous task it will be put into the event queue so it won’t block the main thread.

If the main thread is not blocked then it can do the next task, and your code will continue to run. When the asynchronous task has finished running, it will return data for you to process. There are 3 ways to do this that is callback , Promise and async/await .

Callback

The first and oldest way to deal with asynchronous JavaScript in JavaScript is to use callbacks. A callback is an asynchronous function passed to another function as a parameter on call. When the function finishes running, it will “call back” the passed callback function.

This callback function will not be called, not executed, or do anything until the main function has finished running. This function will not block the main thread so the main thread will be able to do other things. Event listener is one of the callbacks that we often use.

addEventListener() takes 3 parameters. The first parameter is the type of event you want to listen to. The second parameter is the callback function you want to run when the event occurs. The last parameter is an object and is optional.

Callbacks are extremely useful if you cannot know in advance when the data will be available or when the main function will finish running. Take an example of an API call, processing data, and having a delay. It is almost impossible to know in advance when the new API will be complete, as well as the processing of the data.

With the callback, you won’t need to guess when it’s done. You just need to code in the order you want it to be. For example, if the API processing takes time, you can let the data read function as a callback and only execute when there is data. So nothing will block the main thread.

Promise

That second way of handling asynchronous is promises. Promise is a new feature introduced in ES6 that provides an easier way to handle asynchronousness in JavaScript.

A Promise is an object that holds a value. This value will not be shown when you create a Promise. Promise will return this value when it succeeds or fails. There are 3 handler functions you can use to get the value that Promise returns.

These functions are then() , catch() and finally() . To use these handler functions, we attach them to a Promise object. Depending on the status of the Promise, the corresponding handler will be invoked.

  • then() will run when the Promise is successful. You can also sometimes use this to handle a Promise’s failed state.
  • catch() will run only when the Promise fails.
  • finally() will run when the Promise finishes running, regardless of success or failure.

Async / await

The last way to deal with asynchronously is to use async / await. Async / await was introduced in ES8, they are composed of two parts. The first part is the async function. This function will be automatically executed asynchronously. The value it returns is a Promise. Since the Promise is returned, you will have to use the Promise handlers to handle this value.

The second part of async / await is operator await . This operator will be used in conjunction with a Promise. This will cause the async function to pause until that Promise has finished running. It will then take the value of the Promise and let the async function continue to run.

async functions are asynchronous, when being pause by await , the rest of the code is still running normally because that function does not block the main thread. When the Promise finishes running, the async function will continue running and return the value of the Promise.

It is more important that await must be written in an async function otherwise there will be a syntax error

Thank you for reading.

Source: https://blog.alexdevero.com/asynchronous-javascript-code/

Share the news now

Source : Viblo