Asynchronous Operations in JavaScript

Asynchronous-Operations-in-JavaScript-blog.jpg

If you’ve ever used JavaScript to build web applications, you have definitely come across tasks that take time to complete, like fetching data from an API or waiting for a user to click a button. These are examples of asynchronous JavaScript. Unlike traditional code that runs from top to bottom, asynchronous JavaScript allows your program to run multiple operations at the same time without getting stuck. In this blog, you will learn all about asynchronous operations in JavaScript, how asynchronous operations work, and how you can use them properly in your code.

Table of Contents:

What is Asynchronous Programming?

Asynchronous programming is defined as a way of writing code that doesn’t wait for one task to finish before moving on to the next, which means it allows your program to keep running while waiting for something (loading a file, receiving data from a server, or waiting for a timer).

Example:

Javascript

Output:

asynchronous javascript

Explanation: In this example, the setTimeout function is used to execute a function after a specified time. The function that was passed under setTimeout() will be executed asynchronously, which means JavaScript didn’t wait for 2 seconds, and simply executed the first and third console statements. After 2000 milliseconds (or 2 seconds) second console statement is executed.

How Asynchronous Operation Works

One of the biggest challenges in building web applications is managing code that waits for the other task to finish. JavaScript runs in a single thread, which means it processes one line of code at a time. But, this is not sufficient in real-world applications because multiple things happen simultaneously in real-world applications, like loading images, fetching data, and responding to user action. That’s the place where the Callback functions, JavaScript Promises, and async/await in JavaScript are used for handling asynchronous operations.

Callback Functions

Callback function JavaScript is the most common way to handle asynchronous behaviour. A callback is defined as a function that is passed as an argument to another function, and it is called when the main task is done.

Example: Callback function JavaScript

Javascript

Output:

Promises in JavaScript

Explanation: In this example, a callback function in JavaScript is used to manage asynchronous code. You have a function called greet() that accepts two parameters, one is the name, and another is the callback function, which first logs the greeting message “Hello, Intellipaat” and then calls the callback function. The second function, say function simply logs the “Bye Bye!” to the console. Using a callback function helps in managing the flow of code without blocking the rest of the program.

Promises in JavaScript

Using multiple callbacks in the code can create situations like callback hell. To make things simple, JavaScript Promises came into existence. JavaScript promises are defined as another way to work with asynchronous operations like API calls and file loading.

Example: Checking the Eligibility to Vote

Javascript

Output:

Callback Functions JavaScript

Explanation: In this example, you are creating a JavaScript Promise that checks whether you’re eligible to vote or not. You are eligible to vote if your age is greater than or equal to 18, and the promise resolves with the message “You are eligible to vote!”, but if you’re not, then the promise is rejected with the message “You’re not eligible to vote.” Using JavaScript promises is the recommended way to deal with asynchronous programming in JavaScript.

Async Await in JavaScript

Async and Await in JavaScript are built on top of Promises, and they simplify the way to handle asynchronous operations by promises. The async keyword is used to indicate that it is an asynchronous function, and the await keyword is used to tell JavaScript to pause at this line until the promise resolves, without blocking other operations.

Example:

Javascript

Here, the await keyword pauses the function until the data is ready, but it doesn’t block the flow of remaining code. In simple words, the async function returns a promise, and the await keyword waits for a promise to resolve.

Asynchronous Operations in Browsers

You can see multiple asynchronous operations in browsers. Web browsers can handle multiple tasks at the same time, like loading data, responding to clicks, and sending data to the server. JavaScript is a single-threaded language, which means it executes one task at a time. Thus, for managing multiple tasks, the event loop and queues come into the picture. Here is how the browser works:

  1. JavaScript starts by running your code from top to bottom and executes one line at a time. This is known as the main thread. It handles tasks like DOM updation and executing function calls in order.
  2. When your code executes something that takes time (like setTimeout or any fetch() request), it doesn’t wait, and the browser sends that task to a separate system called Web APIs. This API runs in the background, thus your main code keeps running without being blocked.
  3. Your browser is handling the async tasks in the background, but the main thread executes the rest of your code continuously. This makes your application faster and more efficient.
  4. When the asynchronous task is done, the result is stored in a waiting area called the callback queue, where the browser holds completed tasks until the right time to run the task.
  5. The event loop continuously checks the main thread. Once the main thread has finished running all tasks, the event loop takes the first item from the callback queue and runs it.

Conclusion

Understanding how Asynchronous JavaScript works is important for building web applications. Whether you’re working with a Callback function in JavaScript, a JavaScript Promise, or using async await in JavaScript, each of them helps you in managing tasks that take time, and all you can do without blocking other tasks.

To learn more about JavaScript, check out this Web Development course and also explore JavaScript Interview Questions prepared by industry experts.

Asynchronous Operations in JavaScript – FAQs

Q1. What is an asynchronous operation?

An asynchronous operation is defined as a task that runs in the background without blocking other operations.

Q2. What are synchronous operations in JavaScript?

Synchronous operations are defined as the code or task that runs one after another. Each task is required to finish before the next one starts.

Q3. What are Promises in JavaScript?

A JavaScript Promise is defined as a way to handle asynchronous tasks. It represents a value that may not be available initially but will be available in the future.

Q4. What is a Callback function in JavaScript?

A callback function is defined as a function that is passed as an argument to another function, and it is called when the main task is done.

Q5. What is an event loop in Node.js?

An event loop is defined as the part of Node.js that is used to manage asynchronous operations. It continuously checks the main thread, if the main thread is free, the event loop picks one task from the callback queue and executes it.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner