Most of the time we start working with JavaScript we are often confused and puzzled with the concept of asynchronous – asynchronous JS. In this article we will learn about this issue!
1. Asynchrony in JavaScript
Asynchrony in computer programming rising to the occurrence of events completed of the main program flow and ways to deal with such events.
Unlike C / C ++ or Java languages … using multi-thread mechanism. This means that time-consuming tasks can be performed independently on a separate thread without interfering with the main thread. You can still do that and still be able to capture events on the main thread.
But for JavaScript is different, because the JavaScript program is single-thread , all processes execute in a sequential manner, not in parallel. Therefore can not multithreading in JavaScript that use the mechanism to handle asynchronous. Understand roughly in asynchronously, when performing tasks A and B. When starting to perform job A, continue to perform task A without waiting for A to finish. Time to perform AB is the time from A starting until A and B are finished. Thus increasing performance and increasing user experience.
There are 3 common mechanisms to help you do asynchronous in JavaScript: Callback , Promise or Async / await.
2. Callback
When executing a task, it takes a certain amount of time (eg fetch data from API). We perform a function request data and pass another function to handle the returned result ( handleResponse () () ). The handleResponse () function is now acting as the callback () function:
1 2 3 4 5 6 7 8 9 10 11 | const request = require(‘request’); function handleResponse(error, response, body){ if(error){ // Handle error. } else { // Successful, do something with the result. } } request('https://www.somepage.com', handleResponse); |
When the API request starts and ends, handleResponse () is now called. However, when we have to make 2 consecutive requests, request 2 can be executed only when request 1 ends. So we will have to make the 2nd request in the result of request 1. It sounds very complicated but it will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | request('http://www.somepage.com', function (firstError, firstResponse, firstBody) { if(firstError){ // Handle error. } else { request(`http://www.somepage.com/${firstBody.someValue}`, function (secondError, secondResponse, secondBody) { if(secondError){ // Handle error. } else { // Use secondBody for something } }); } }); |
Imagine you have to make a few more requests, the result will certainly be much worse. This is called ** Callback Hell. **
To avoid Callback Hell, you can use a different mechanism. It is a Promise.
3. Promise
Unlike Callback, which needs to provide a callback function, Promise has available methods to call when the function executes success or fail, then () and catch (). It should look like this:
1 2 3 4 5 6 7 8 | someAsyncOperation(someParams) .then(function(result){ // Do something with the result }) .catch(function(error){ // Handle error }); |
So similar to Callbacl Hell, what does the promise look like ??
1 2 3 4 5 6 7 8 9 10 11 12 13 | const axios = require(‘axios’); axios.get(‘http://www.somepage.com') .then(function (response) { // Reponse being the result of the first request // Returns another promise to the next .then(..) in the chain return axios.get(`http://www.somepage.com/${response.someValue}`); }) .then(function response { // Reponse being the result of the second request // Handle response }) .catch(function (error) { // Handle error. }); |
It is clear that the program has become clearer and there are no more nested callback functions like the callback mechanism
4. Async / await
Async / await is a special syntax that helps you declare that the function will perform an asynchronous action. Await to declare waiting for the result of an asynchronous operation inside an action with the async keyword.
1 2 3 4 5 | async function getSomeAsyncData(value){ const result = await fetchTheData(someUrl, value); return result; } |
And even if you make many requests, it is much simpler, isn't it. And in my opinion, this is probably the best way to handle asynchronous in JavaScript, in your opinion?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | async function fetchTheFirstData(value){ return await get("someUrl", value); } async function fetchTheSecondData(value){ return await getFromDatabase(value); } async function getSomeData(value){ try { const firstResult = await fetchTheFirstData(value); const result = await fetchTheSecondData(firstResult.someValue); return result; } catch(error){ // Every error thrown in the whole “awaitable” chain will end up here now. } } |
Conclude:
Above are some basic knowledge of handling asynchronous JavaScript with callback, promise and async / await. This article doesn't cover Promise or async / await, it just helps you to see the basic usage, as well as their advantages compared to using a regular callback.
References: