Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 25 - Async/Await in JavaScript

Async/Await is a modern way to handle asynchronous operations in JavaScript. It makes asynchronous code look and behave more like synchronous code, improving readability.


Example 1: Using async and await with a Promise

async function fetchData() {
    return "Data received!";
}

fetchData().then(result => console.log(result)); // Output: Data received!
  • The function fetchData automatically returns a Promise.

Explanation

  • The async keyword is used to declare an asynchronous function.
  • The await keyword pauses the execution of an async function until the Promise resolves or rejects.
  • await can only be used inside an async function.

Example 2: Awaiting a Promise

function getUser() {
    return new Promise(resolve => {
        setTimeout(() => resolve({ name: "Alice", age: 25 }), 2000);
    });
}

async function showUser() {
    let user = await getUser();
    console.log(`User: ${user.name}, Age: ${user.age}`);
}

showUser();
  • The function showUser() waits for getUser() to complete before logging the result.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson25-async-await.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 25 - Async/Await</title>
      </head>
      <body>
      <script>
         function fetchData() {
             return new Promise(resolve => {
                 setTimeout(() => resolve("Hello, Async/Await!"), 1500);
             });
         }
      
         async function displayMessage() {
             let message = await fetchData();
             console.log(message);
         }
      
         displayMessage();
      </script>
      </body>
      </html>
  3. Save the File.

  4. Preview in Browser and Check Console Output.


Experiment

  1. Modify getUser() to reject if no user is found and handle it with try...catch.
  2. Create an async function that fetches and logs two pieces of data in sequence.

Key Takeaways

  • async functions return a Promise.
  • await pauses execution until the Promise resolves.
  • try...catch can be used to handle errors in async functions.