JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Async/Await

Async/Await is a modern JavaScript syntax feature introduced to simplify the handling of asynchronous operations, providing a clearer and more readable way to write asynchronous code compared to older approaches like callbacks and promises. It is syntactic sugar built on top of Promises, designed to make asynchronous code feel more like synchronous code, which is easier to understand and maintain.

Why We Need Async/Await?

Async/Await addresses several challenges posed by older asynchronous handling techniques:

  • Readability: Nested callbacks and even promise chains can lead to complex code structures that are hard to follow, often referred to as "callback hell" or "pyramid of doom". Async/Await flattens the structure and reduces boilerplate code.
  • Error Handling: Using Async/Await makes it simpler to handle errors uniformly with try/catch blocks, unlike in promises which require chaining .catch() methods.
  • Synchronization: Managing the sequence of asynchronous operations is more intuitive with Async/Await, as it allows developers to write code that looks synchronous, even though it executes asynchronously.

Syntax

The syntax for Async/Await is straightforward:

Javascript
Javascript
. . . .

In the above syntax:

  • async Keyword: Placed before a function declaration to indicate that the function is asynchronous. This transforms the function into one that returns a promise.
  • await Keyword: Used inside async functions to pause the function's execution until the promise resolves. It can only be used within functions defined with async.

Example 1: Basic Async/Await Usage for Fetching Data

Javascript
Javascript
. . . .

Explanation:

  • async function getUserData() {...}: This line defines an asynchronous function named getUserData. The async keyword allows the use of await inside the function and means the function returns a Promise.
  • console.log('Fetching data...'): Outputs a message to the console indicating that data fetching has started.
  • const response = await fetch('https://dummyjson.com/products/1'): The await keyword pauses the function's execution until the Promise returned by fetch() is resolved, i.e., until the data is fetched from the provided URL. The result is stored in response.
  • const data = await response.json(): After fetching, the response body is processed as JSON. The execution is paused again until this asynchronous operation completes. The resulting data is stored in data.
  • console.log('Data received:', data): Finally, the fetched and processed data is logged to the console.

Example 2: Async/Await with Error Handling

Javascript
Javascript
. . . .

Explanation:

  • try {...} catch (error) {...}: This block is used to handle errors that might occur during the asynchronous operations. If an error occurs in the try block, execution moves to the catch block.
  • console.log('Fetching user data...'): This logs a message indicating the start of the operation.
  • const response = await fetch('https://api.example.com/user'): Makes a network request to fetch user data. If this request fails (e.g., network error or invalid URL), the error will be caught by the catch block.
  • const data = await response.json(): Parses the response into JSON. If the response is not in valid JSON format, it will throw an error that is caught by the catch block.
  • console.log('User data:', data): If there are no errors, logs the successfully fetched and parsed data.
  • catch (error): Catches any errors from the fetch call or JSON parsing and logs an appropriate error message to the console.

These examples highlight how async and await enhance readability and error management in asynchronous JavaScript operations, allowing for cleaner and more intuitive handling of operations that would otherwise require more complex promise chains or callback functions.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next