Async/Await in JavaScript

Video Tutorial
FREE
Promises and Async Await thumbnail
This video belongs to
JavaScript Course With Certification: Unlocking the Power of JavaScript
9 modules
Certificate
Topics Covered

Async Await in JavaScript are powerful keywords that help manage asynchronous operations more smoothly. They allows you to write code that looks synchronous but actually performs tasks in the background, like fetching data from the internet. This makes your code easier to read and maintain, avoiding the complexity of handling promises with then/catch. With Async/Await, you can write cleaner and more intuitive code for asynchronous tasks.

What is Async Function?

An async function in JavaScript is a function declared with the async keyword. The async function always returns a promise. If the function returns a value, the corresponding promise will be fulfilled with that value. Conversely, if the async function generates an error, the promise will be rejected with the said error.

The beauty of async functions is that they make asynchronous code look and behave a little more like synchronous code, which helps manage complex chains of promises and callbacks more straightforwardly.

Example:

Output:

loadMessage is an async function that simulates a data retrieval operation and returns a string message. The essence of the example remains the same, illustrating how async functions return a promise, which can then be handled using .then() to process the resolved value, in this case, logging the message to the console. This showcases the use of async/await for cleaner, more readable asynchronous code handling.

What is Await Function?

The await keyword in JavaScript is used inside async functions to pause the execution until a Promise is resolved, effectively waiting for the asynchronous operation to complete before moving on. await can only be used within functions declared with async.

Here's a similar example that demonstrates how to use await within an async function, with a slight modification to illustrate the concept:

Output:

In this example, showMessage is an async function that uses await to simulate waiting for an asynchronous operation, in this case, simply awaiting a string.

How async/await Works

Async/await in JavaScript fundamentally changes how asynchronous code is written and executed, making it more readable and easier to understand. By utilizing async await JavaScript, the async is used to define an asynchronous function, which returns a promise. Within such a function, the await keyword, a cornerstone of async await JavaScript, is used to pause the execution of the function until a promise is resolved or rejected. This approach effectively makes the asynchronous code look and behave like synchronous code, showcasing the power and simplicity of async await JavaScript in modern web development.

To illustrate how async/await operates, let's consider a scenario involving a network request simulation with setTimeout to mimic a delay, which is a common use case for async/await:

Output:

In this example, we have a fetchUserData promise that simulates a network request taking 3 seconds to complete. The getUserData async function demonstrates how to use await, waiting for the promise to resolve before continuing with the execution.

Key Points:

  • The await pauses the execution of the getUserData function until fetchUserData is resolved, without blocking the main thread. This means other JavaScript operations can run in the meantime.
  • console.log('Fetching user data...') is executed immediately when getUserData is called, indicating the start of data fetching.
  • The next line with the await keyword pauses further execution within getUserData until fetchUserData resolves. Once it does, "User data fetched" is logged, followed by "Processing complete".
  • This demonstrates how async/await handles asynchronous operations in a more readable and manageable way, resembling synchronous behavior.

Note:

  • await can only be used within functions declared with async, and it ensures that JavaScript waits for the promise to settle (either resolve or reject) before proceeding.
  • This approach simplifies handling multiple asynchronous operations in sequence, making the code appear as though it's executing step-by-step, similar to synchronous code.

How to Handle Errors in Async/Await

Error Handling with Try/Catch

The try block allows you to wrap one or more lines of code that may throw an error, while the catch block lets you define how to respond to that error. This approach provides a clear, structured way to manage errors, making your code cleaner and more reliable.

Here's an example to illustrate error handling with async/await:

In this scenario, the fetchUserDetails function attempts to fetch user details from a fictional API. The await keyword is used to wait for the fetch operation and the subsequent conversion to JSON to complete. If either of these operations fails (for instance, if the network request is unsuccessful or the response cannot be parsed as JSON), an error will be thrown.

The catch block catches this error, allowing you to handle it gracefully, such as by logging it to the console, displaying a message to the user, or performing any other error handling measures your application requires.

How to Use Async/Await in IIFE and Arrow Functions

Using async/await in JavaScript within Immediately Invoked Function Expressions (IIFEs) and arrow functions provides a concise and effective way to execute asynchronous code instantly. This approach eliminates the need to define a separate async function, showcasing the flexibility and power of async await JavaScript for streamlined asynchronous execution.

Async/Await in IIFEs

An IIFE is a function that runs as soon as it is defined. It's a common pattern for encapsulating and executing code in its own scope. To use async/await within an IIFE, you simply define the function as async and then immediately invoke it:

This example demonstrates how to wrap an asynchronous operation—such as fetching data, reading a file, or any promise-based task—inside an async IIFE. It allows for immediate execution of async code in a clean and self-contained manner.

Async/Await in Arrow Functions

Arrow functions provide a succinct syntax for writing functions in JavaScript. When combined with async/await, they enable you to write concise asynchronous code. Here's how you can use async/await in arrow functions:

This example shows an async arrow function named fetchData that fetches data from a URL and logs it. The function is defined with the async keyword before the parameters list, indicating that it can use await inside its body. After its definition, fetchData is called like any other function.

Why Use the async/await Syntax?

  • Async await javascript allows asynchronous code to be written in a manner that resembles synchronous code, making it easier to understand and maintain.
  • Errors in async await javascript can be caught using simple try/catch blocks, a familiar syntax for most JavaScript developers, which makes error handling more intuitive and centralized.
  • Since async await javascript allows asynchronous code to look and behave more like synchronous code, it simplifies the debugging process. Breakpoints and step-through debugging work more intuitively.
  • Await pauses the execution of async functions, allowing for sequential execution of asynchronous operations without the callback hell or nesting associated with promises.
  • With async and await in javascript, you can also efficiently manage concurrent operations by using Promise.all(), making it easier to optimize performance without complicating the code.

Supported Browsers

The async/await syntax, introduced in ECMAScript 2017 (ES8), is widely supported across modern web browsers. However, considering the ever-evolving nature of web technologies and the diversity of user devices, it's important to be aware of the compatibility landscape.

  • Google Chrome: Supported since version 55.
  • Mozilla Firefox: Supported since version 52.
  • Safari: Supported since version 10.1
  • Microsoft Edge: Supported since version 15. Note that legacy versions of Internet Explorer do not support async/await.
  • Opera: Supported since version 42.

Conclusion

  • Async await javascript works on the concept of Promise. Async defines the fulfillment of a promise and returns a promise.
  • We use async before the function that allows us to return promise-based codes.
  • Await can be used only in async functions. It is used to make the function wait until and unless the promise is resolved or rejected and then returns the result.
  • We use the try...catch method for error handling in async/await.
  • Async await javascript makes asynchronous code that is easy to read and write.