Table of contents
A way of performing non-blocking operations in JavaScript, which means that the code does not stop executing while it waits for a long-running task (such as a network request) to complete can be refers to as Asynchronous JacaScript. In contrast, synchronous code would block and wait for the result before continuing.
Accoring to MDN, Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.
Considering the Image below, we will see the difference between Synchronous and Asynchronous Process. In synchronous process we see that while process A
is being executed, it is being halted to finish the process B
for response before continuing the process. While in asynchronous process we see that process A
is able to do other task while process B
is processing the task until process A
get back the response.
Asynchronous JavaScript works exactly like the illustration in the image.
There are several ways to use asynchronous JavaScript in a project, depending on the requirements and the complexity of the project. We will discuss here some common approaches:
Callback: This is a basic and simple way to make asynchronous code in JavaScript. A callback function is passed as an argument to another function and is executed when a certain event or action has been completed.
Here's an example to illustrate the use of callbacks in JavaScript:
function fetchName(callback) { setTimeout(() => { callback({ nameApi: "https//www.your_api_link.com" }); }, 1000); } fetchName(function (nameApi) { console.log(https//www.your_api_link.com); // Output: Your API results });
In this example, the
fetchName
function takes acallback
argument, which it will execute after a one-second timeout. ThefetchName
function could represent an API call or some other long-running operation. The callback function takes thenameApi
returned fromfetchName
and logs it to the console.Know that JavaScript is single-threaded, so without callbacks, the whole program would block and wait for the
fetchName
function to complete before doing anything else. With callbacks, the program can continue to execute other code whilefetchName
is running, and thecallback
function will be called as soon as the data is available.Promises: Promises are a more advanced way to handle asynchronous code in JavaScript. It is an object representing the eventual completion or failure of an asynchronous operation. They provide a way to register a callback that will be called when an asynchronous operation completes, similar to how a callback is passed to a function.
It offer a more concise and readable syntax compared to callbacks, and also provide a mechanism for chaining asynchronous operations together. It can be in one of three states: pending, fulfilled, or rejected. Once a Promise is fulfilled or rejected, its value can be accessed using the
then
orcatch
methods, respectively.Here's an example that illustrates the use of Promises in JavaScript:
function fetchName() { return new Promise((resolve) => { setTimeout(() => { resolve({ nameApi: "https//www.your_api_link.com" }); }, 1000); }); } fetchName() .then((nameApi) => { console.log(nameApi); // Output: Your API result }) .catch((error) => { console.error(error); });
In this example, the
fetchName
function returns a Promise that will resolve with{ nameApi: "https://your_api_link" }
after a one-second timeout. Thethen
method is called on the returned Promise, which takes a callback function that will be executed as soon as the Promise is resolved. ThenameApi
argument passed to the callback is the resolved value of the Promise, which is logged to the console.Promises provide a mechanism for handling errors as well, by returning a rejected Promise instead of a resolved one. In that case, the
catch
method can be used to handle the error in this example, if the Promise returned byfetchName
is rejected, thecatch
method will be called with the error as its argument, which will be logged to the console.Async/Await: It provides a way to write asynchronous code that looks and behaves more like synchronous code. It is built on top of Promises and makes it easier to write and read asynchronous code by allowing you to use the
await
keyword to wait for a Promise to resolve before moving on to the next line of code. Here's an example that illustrates the use ofasync
/await
in JavaScript:async function fetchName() { return new Promise((resolve) => { setTimeout(() => { resolve({ name: "https://www.your_api_link.com" }); }, 1000); }); } async function main() { const name = await fetchName(); console.log(name); } main();
In this example, the
fetchName
function returns a Promise as before, but this time it's declared as anasync
function. Themain
function is also declared asasync
, which allows us to use theawait
keyword within it. Theawait
keyword is used to wait for thefetchName
function to resolve, and the resolved value is stored in thename
constant. Once the Promise is resolved, the next line of code is executed and the resolved value is logged to the console.It's important to know that an
async
function always returns a Promise, even if it doesn't contain anyawait
statements. Also,async
functions are always executed asynchronously, so even if you don't use theawait
keyword, the code inside the function won't block the execution of the rest of the program.
Uses of Asynchronous JavaScript
Asynchronous JavaScript can be used in a variety of contexts to handle long-running operations without blocking the main thread and affecting the performance of the page or application. Here are some common use cases:
API Requests: It is commonly used to make API requests to fetch data from a server which allows the page or application to continue executing while the API request is in progress, without freezing or blocking the UI.
User Interactions: It is also used to handle user interactions like clicks, hover, and form submissions. This allows the application to respond to the user's actions in a timely manner, without freezing the UI while waiting for a response from the server.
Background Tasks: It is also used to perform background tasks, such as updating data, sending notifications, or polling for new data, without blocking the main thread and affecting the performance of the page or application.
File Uploads and Downloads: It can be used to handle file uploads and downloads in a way that allows the user to continue using the page or application while the file is being transferred in the background.
Animations: It is also used to perform animations and transition effects, without freezing the UI while the animation is in progress.
Data Processing: It can be used to process large amounts of data, without freezing the UI while the data is being processed.
Asynchronous JavaScript is a powerful tool that allows developers to write highly responsive and interactive web applications that provide a seamless user experience.
Importance of Asyncronous Javascript
Asynchronous JavaScript is an important tool for building modern, responsive, and scalable web applications. Here are some of the key benefits and reasons why it's important:
Improved Performance: By allowing long-running operations to be performed asynchronously, it helps to improve the overall performance and responsiveness of the page or application. This is because it prevents the main thread from being blocked, which would otherwise result in a frozen or unresponsive UI.
Better User Experience: By allowing the application to continue executing while waiting for a response from the server or performing a long-running operation, asynchronous JavaScript helps to provide a better user experience. This is because the user is able to continue using the page or application without being blocked or encountering any lag or delay.
Increased Scalability: By enabling the application to handle multiple tasks simultaneously, asynchronous JavaScript helps to improve scalability. This is because it allows the application to continue executing even when one task is blocked, without affecting the performance of the rest of the application.
Simplified Code: It provide more intuitive and easier-to-read syntax for writing asynchronous code, it helps to simplify the code and make it easier to maintain and debug.
Better Resource Utilization: Multiple tasks can be allow to be executed simultaneously, asynchronous JavaScript helps to make better use of system resources, such as CPU and memory, which can lead to improved performance and responsiveness.
In conclusion, asynchronous JavaScript is a critical tool for building modern and responsive web applications that provide a seamless user experience. Its use of non-blocking operations helps to improve performance, scalability, and resource utilization, while also simplifying the code and making it easier to maintain and debug.
If you find this article interesting, leave a like and share to other. Thank you.