DEV Community

Lokesh
Lokesh

Posted on

Async/Await in JavaScript

Async/await makes working with Promises easier and helps us write asynchronous code in a clean, readable way.

Let's understand it with simple examples!

1. What Is Async/Await?

async and await are JavaScript keywords used to work with asynchronous operations.

  • async is used to declare an asynchronous function.
  • await waits for a Promise to settle before continuing the execution of that async function.

2. Understanding async

When we use async before a function, that function always returns a Promise.

async function greet() {
    return "Hello, JavaScript!";
}

greet().then((message) => {
    console.log(message);
});
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, JavaScript!
Enter fullscreen mode Exit fullscreen mode

Even though we return a normal string, the async function returns a Promise that fulfills with that string.

3. Understanding await

The await keyword waits for a Promise's result before continuing inside the async function.

function getData() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("Data received!");
        }, 2000);
    });
}

async function displayData() {
    const result = await getData();
    console.log(result);
}

displayData();
Enter fullscreen mode Exit fullscreen mode

Output after approximately two seconds:

Data received!
Enter fullscreen mode Exit fullscreen mode

Here, await waits for the Promise returned by getData() to fulfill before assigning its value to result.

Note: await pauses the async function, not the entire JavaScript application.

4. Using Async/Await with Fetch API

We often use async/await when fetching data from an API.

async function getProducts() {
    const response = await fetch(
        "https://fakestoreapi.com/products"
    );

    const products = await response.json();

    console.log(products);
}

getProducts();
Enter fullscreen mode Exit fullscreen mode

Let's understand the code:

  1. fetch() requests product data from the API.
  2. await waits for the response.
  3. response.json() reads and parses the response body.
  4. await waits for the parsed data.
  5. console.log() displays the products.

5. Handling Errors with Try/Catch

Sometimes, an API request may fail. We can use try...catch to handle errors.

async function getProducts() {
    try {
        const response = await fetch(
            "https://fakestoreapi.com/products"
        );

        if (!response.ok) {
            throw new Error("Failed to fetch products");
        }

        const products = await response.json();

        console.log(products);
    } catch (error) {
        console.log("Error:", error.message);
    }
}

getProducts();
Enter fullscreen mode Exit fullscreen mode

The try block contains the code we want to execute. If an error is thrown or an awaited Promise rejects, the catch block handles it.

Checking response.ok is important because fetch() does not automatically throw an error for HTTP responses such as 404 Not Found.

6. Async/Await vs. Then/Catch

Both approaches can handle Promises.

Using .then():

fetch("https://fakestoreapi.com/products")
    .then((response) => response.json())
    .then((products) => console.log(products))
    .catch((error) => console.log(error));
Enter fullscreen mode Exit fullscreen mode

Using async/await:

async function getProducts() {
    try {
        const response = await fetch(
            "https://fakestoreapi.com/products"
        );

        const products = await response.json();

        console.log(products);
    } catch (error) {
        console.log(error);
    }
}

getProducts();
Enter fullscreen mode Exit fullscreen mode

Both approaches work with Promises. Many developers prefer async/await because it can make asynchronous code easier to read.

Conclusion

Async/await is an important JavaScript concept, especially when working with APIs and modern frameworks like React.

Remember:

  • async makes a function return a Promise.
  • await waits for a Promise's result inside an async function.
  • try...catch helps handle errors.
  • Async/await makes asynchronous code easier to read.

Keep practising these examples to improve your JavaScript skills.

Happy Coding! 🚀

Top comments (0)