A brief intro to asynchronous programming in JavaScript

Vishal
5 min readApr 23, 2023

--

Asynchronous programming is a crucial aspect of modern web development, where long-running tasks, such as making network requests, can cause the user interface to freeze and become unresponsive. JavaScript, the primary language of the web, provides several ways to handle asynchronous operations, including callbacks, promises, and the relatively new async/await syntax.

In this article, we’ll dive into the concepts of async and await in JavaScript and see how they make it easier to write asynchronous code that is more readable, maintainable, and error-free.

What is Asynchronous Programming?

Asynchronous programming is a programming paradigm that allows a program to perform tasks concurrently, without blocking the execution of other tasks. In JavaScript, this is achieved using callbacks, promises, and async/await.

Callbacks are functions that are passed as arguments to other functions and are called when a task completes. Promises provide a way to handle asynchronous operations in a more organized and predictable way, chaining multiple operations and handling errors more effectively.

Async and Await in JavaScript

Async/await is a newer way of handling asynchronous operations in JavaScript that makes code more readable and easier to write. Async functions return a promise, and the await keyword is used to pause the execution of the function until a promise is resolved. Let’s see how this works in practice.

Example 1:

First, we’ll create a simple function that returns a promise that resolves after a certain time.

Sample function that returns a promise

This function takes a time argument and returns a promise that resolves after the specified time has elapsed. We can use this function to simulate an asynchronous operation that takes some time to complete.

Now, let’s create an async function that calls this function and waits for the promise to resolve.

An async function that waits for promise to resolve

n this function, we use the async keyword to mark it as asynchronous, and we use the await keyword to pause the execution of the function until the promise returned by the wait function is resolved. This way, we can write code that looks like synchronous code but is actually asynchronous.

When we call the doSomething function, it will log “start,” wait for two seconds, and then log “end.”

The function logs start and end(after waiting for 2 seconds)

Advantages of Async/Await

The async/await syntax offers several benefits over the traditional callback and promise-based approaches to asynchronous programming:

  1. Readability: Async/await code is more readable and easier to follow than nested callbacks and promise chains. It allows developers to write code that looks like synchronous code, making it easier to reason about the flow of the program.
  2. Error handling: Async/await provides a natural way to handle errors in asynchronous code, using try/catch blocks. This makes it easier to handle errors in a way that is consistent with synchronous code.
  3. Maintainability: Async/await code is more maintainable than nested callbacks and promise chains. It’s easier to modify and refactor code when using async/await, and it makes it easier to understand the codebase when working with other developers.

Let us take a look at a few more code examples to illustrate how async/await works in JavaScript.

Example 2:

Fetching Data from an API

One common use case for async/await is when making network requests to an API. Let’s take a look at an example of how we might use async/await to fetch data from an API using the fetch() function.

An example denoting the use of fetch() function

In this example, we define an async function called fetchUserData() that uses the fetch() function to make a request to the JSONPlaceholder API for user data. We use the await keyword to pause execution of the function until the response is received, and then we call the json() method on the response object to parse the data. Finally, we log the data to the console.

We also use a try/catch block to handle any errors that might occur while making the network request or parsing the response.

Example 3:

Looping Through an Array

Another common use case for async/await is when looping through an array of items and performing an asynchronous operation on each item. Here’s an example of how we might use async/await to loop through an array of URLs and fetch data from each one.

Looping through an array of URLs using the concept of async/await

In this example, we define an array of URLs and an async function called fetchAllData() that uses the Promise.all() method to make parallel requests to each URL using the fetch() function. We then use the await keyword to pause execution of the function until all responses are received, and then we call the json() method on each response object to parse the data.

We use another Promise.all() method to wait for all of the JSON data to be parsed, and then we log the array of data to the console.

Conclusion

Async/await is a powerful and convenient way to handle asynchronous operations in JavaScript. Whether you’re fetching data from an API or performing some other kind of asynchronous operation, async/await can simplify your code and make it easier to reason about. With its readability, error handling, and maintainability benefits, async/await is quickly becoming the preferred way to handle asynchronous programming in JavaScript.

If you wish to see more of such exciting content, kindly please do follow, since it motivates me to post better articles. Thank you !

--

--

Vishal

Full Stack Developer, passionate about machine learning.