JavaScript Async/Await

The async and await keywords in JavaScript simplify the management of asynchronous code by making it easier to write and read. They provide a way to handle Promises in a more synchronous-looking manner.

Key Topics

Async Functions

An async function always returns a Promise. Inside an async function, you can use the await keyword to wait for a Promise to resolve or reject.

async function fetchData() {
    return "Data fetched successfully!";
}
fetchData().then((data) => {
    console.log(data);
});

Output

> Data fetched successfully!

Explanation: The fetchData function is declared with async, allowing it to return a resolved Promise with the provided message.

Using Await

The await keyword pauses the execution of an async function until the Promise is resolved or rejected.

async function fetchData() {
    const promise = new Promise((resolve) => {
        setTimeout(() => resolve("Data fetched successfully!"), 2000);
    });
    const result = await promise;
    console.log(result);
}
fetchData();

Output

> Data fetched successfully!

Explanation: The fetchData function waits for the Promise to resolve before logging the result, creating a more synchronous flow.

Error Handling

Errors in async functions can be caught using a try...catch block.

async function fetchData() {
    try {
        const promise = new Promise((_, reject) => {
            setTimeout(() => reject("Error fetching data!"), 2000);
        });
        const result = await promise;
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}
fetchData();

Output

> Error fetching data!

Explanation: The try...catch block ensures that errors in the Promise are handled gracefully within the fetchData function.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating the use of async and await to fetch and display data dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Async/Await in DOM</title>
</head>
<body>
    <button onclick="loadData()">Load Data</button>
    <p id="output"></p>

    <script>
        async function fetchMessage() {
            const promise = new Promise((resolve) => {
                setTimeout(() => resolve("Data loaded successfully!"), 1500);
            });
            return await promise;
        }
        async function loadData() {
            const message = await fetchMessage();
            document.getElementById("output").textContent = message;
        }
    </script>
</body>
</html>

Key Takeaways

  • Async Functions: Always return a Promise, simplifying asynchronous code.
  • Await: Pauses execution until a Promise resolves, creating a synchronous-like flow.
  • Error Handling: Use try...catch to manage errors gracefully in async functions.
  • DOM Integration: Use async/await to dynamically update UI content after asynchronous tasks.