JavaScript async await Practice Questions with Solutions

Introductions

async and await make asynchronous JavaScript easier to read and understand. They are built on top of Promises and are commonly used when working with APIs, database requests, timers, and other operations that finish later.

In this chapter, you will practice creating async functions, using await, handling errors with try...catch, returning values from async functions, and working with multiple asynchronous operations. JavaScript async await practice questions with solutions help to understand the concepts.

Question 1: Create a Basic async Function

Problem

Create an async function that returns a simple message.

Solution

async function showMessage() {
    return "Hello from async function!";
}

showMessage().then(function(message) {
    console.log(message);
});

Output

Hello from async function!

Step-by-step Explanation

  1. The async keyword makes showMessage() an asynchronous function.
  2. An async function always returns a Promise.
  3. The string is automatically wrapped in a fulfilled Promise.
  4. .then() receives the returned value.

Even though the function returns a string:

return "Hello from async function!";

the function actually returns a Promise.


Question 2: Use await with a Promise

Problem

Create a Promise that resolves after 2 seconds and use await to get its result.

Solution

function getMessage() {
    return new Promise(function(resolve) {

        setTimeout(function() {
            resolve("Data received!");
        }, 2000);

    });
}

async function showMessage() {

    const message = await getMessage();

    console.log(message);
}

showMessage();

Output

After approximately 2 seconds:

Data received!

Step-by-step Explanation

  1. getMessage() returns a Promise.
  2. The Promise waits for approximately 2 seconds.
  3. resolve() sends the result.
  4. await waits for that Promise to settle.
  5. The result is stored in message.
  6. The message is displayed.

The important line is:

const message = await getMessage();

await makes the code wait for the Promise result inside the async function.


Question 3: Use async/await with a Simple Calculation

Problem

Create an async function that waits for a Promise containing the number 10 and then doubles the number.

Solution

function getNumber() {
    return Promise.resolve(10);
}

async function calculate() {

    const number = await getNumber();

    const result = number * 2;

    console.log(result);
}

calculate();

Output

20

Step-by-step Explanation

  1. getNumber() returns a fulfilled Promise.
  2. await gets the value 10.
  3. The value is stored in number.
  4. number * 2 gives 20.
  5. The result is displayed.

Question 4: Handle Errors with async/await

Problem

Create a rejected Promise and handle the error using try...catch inside an async function.

Solution

function getData() {
    return Promise.reject("Unable to get data.");
}

async function loadData() {

    try {

        const data = await getData();

        console.log(data);

    } catch (error) {

        console.log(error);

    }
}

loadData();

Output

Unable to get data.

Step-by-step Explanation

  1. getData() returns a rejected Promise.
  2. await encounters the rejection.
  3. JavaScript moves to the catch block.
  4. The error is stored in error.
  5. The error message is displayed.

This is one of the most common patterns:

async function example() {

    try {
        const result = await somePromise();
    } catch (error) {
        console.log(error);
    }

}

Question 5: Use async/await with setTimeout()

Problem

Create a reusable function that waits for 3 seconds and then returns "Finished!".

Solution

function waitThreeSeconds() {

    return new Promise(function(resolve) {

        setTimeout(function() {

            resolve("Finished!");

        }, 3000);

    });
}

async function startProcess() {

    console.log("Starting...");

    const message = await waitThreeSeconds();

    console.log(message);
}

startProcess();

Output

Immediately:

Starting...

After approximately 3 seconds:

Finished!

Step-by-step Explanation

  1. waitThreeSeconds() creates a Promise.
  2. setTimeout() waits approximately 3 seconds.
  3. The Promise resolves after the delay.
  4. await waits for the result.
  5. "Finished!" is stored in message.
  6. The message is displayed.

Question 6: Return a Value from an async Function

Problem

Create an async function that calculates the square of a number and returns the result.

Solution

async function square(number) {

    return number * number;
}

square(6).then(function(result) {

    console.log(result);

});

Output

36

Step-by-step Explanation

  1. square() is an async function.
  2. It calculates 6 * 6.
  3. The result is 36.
  4. Because the function is async, the result is returned through a Promise.
  5. .then() receives 36.

You can think of:

return 36;

inside an async function as producing a fulfilled Promise containing 36.


Question 7: Run Multiple await Operations

Problem

Create two asynchronous functions. Wait for both operations one after another and display their results.

Solution

function getUserName() {

    return new Promise(function(resolve) {

        setTimeout(function() {
            resolve("Rahul");
        }, 1000);

    });
}

function getCourse() {

    return new Promise(function(resolve) {

        setTimeout(function() {
            resolve("JavaScript");
        }, 1000);

    });
}

async function showUser() {

    const name = await getUserName();

    const course = await getCourse();

    console.log("Name:", name);
    console.log("Course:", course);
}

showUser();

Output

After the operations finish:

Name: Rahul
Course: JavaScript

Step-by-step Explanation

  1. getUserName() returns a Promise.
  2. await waits for the username.
  3. getCourse() returns another Promise.
  4. The second await waits for the course.
  5. Both values are then displayed.

This approach is easy to read, but the two operations are performed sequentially.


Question 8: Use Promise.all() with async/await

Problem

Run three Promises together using Promise.all() and await.

Solution

function getHTML() {
    return Promise.resolve("HTML");
}

function getCSS() {
    return Promise.resolve("CSS");
}

function getJavaScript() {
    return Promise.resolve("JavaScript");
}

async function getSkills() {

    const skills = await Promise.all([
        getHTML(),
        getCSS(),
        getJavaScript()
    ]);

    console.log(skills);
}

getSkills();

Output

[
    "HTML",
    "CSS",
    "JavaScript"
]

Step-by-step Explanation

  1. Three functions return Promises.
  2. All three Promises are passed to Promise.all().
  3. await waits until all of them fulfill.
  4. The results are returned as an array.
  5. The array is stored in skills.

This is useful when multiple independent asynchronous operations need to complete.


Question 9: Build an async Data Loading Function

Problem

Create a function that simulates loading student data and displays it using async/await.

Solution

function getStudent() {

    return new Promise(function(resolve) {

        setTimeout(function() {

            resolve({
                name: "Aman",
                age: 19,
                course: "JavaScript"
            });

        }, 2000);

    });
}

async function displayStudent() {

    console.log("Loading student...");

    const student = await getStudent();

    console.log("Name:", student.name);
    console.log("Age:", student.age);
    console.log("Course:", student.course);
}

displayStudent();

Output

Immediately:

Loading student...

After approximately 2 seconds:

Name: Aman
Age: 19
Course: JavaScript

Step-by-step Explanation

  1. getStudent() returns a Promise.
  2. The Promise simulates a delayed operation.
  3. After approximately 2 seconds, it resolves with an object.
  4. await waits for the object.
  5. The object is stored in student.
  6. Individual properties are accessed using dot notation.

Question 10: Build a Complete async/await Example with Error Handling

Problem

Create a simulated login system using async/await. Show a success message for correct credentials and handle incorrect credentials with try...catch.

Solution

function login(username, password) {

    return new Promise(function(resolve, reject) {

        setTimeout(function() {

            if (username === "admin" && password === "1234") {

                resolve("Login successful!");

            } else {

                reject(new Error("Invalid username or password."));

            }

        }, 1500);

    });
}

async function startLogin() {

    try {

        console.log("Checking login...");

        const message = await login("admin", "1234");

        console.log(message);

    } catch (error) {

        console.log("Login failed:", error.message);

    }

}

startLogin();

Output

Immediately:

Checking login...

After approximately 1.5 seconds:

Login successful!

If incorrect credentials are used:

const message = await login("admin", "wrong");

The output becomes:

Checking login...
Login failed: Invalid username or password.

Step-by-step Explanation

  1. login() returns a Promise.
  2. setTimeout() simulates a delayed login request.
  3. The username and password are checked.
  4. Correct credentials call resolve().
  5. Incorrect credentials call reject().
  6. await waits for the Promise.
  7. Successful results are handled normally.
  8. Rejected Promises move execution to catch.
  9. error.message displays the reason for failure.

This pattern is very useful when working with real asynchronous operations such as API requests.

Key Takeaways

  • async is used to create an asynchronous function.
  • An async function always returns a Promise.
  • await is used inside an async function to wait for a Promise’s result.
  • await makes asynchronous code easier to read.
  • try...catch is commonly used with async/await for error handling.
  • async/await does not remove the asynchronous nature of JavaScript.
  • Promise.all() can be combined with await.
  • Multiple independent operations can often be started together with Promise.all().
  • await pauses the execution of the current async function, not the entire JavaScript program.
  • Async functions can return normal values, which are automatically wrapped in fulfilled Promises.
  • await can be used with any Promise-like value.
  • async/await is widely used when working with APIs and other asynchronous operations.

FAQs

1. What is async in JavaScript?

The async keyword makes a function asynchronous and causes the function to return a Promise.

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

You can handle its result with:

greet().then(function(message) {
    console.log(message);
});

2. What is await in JavaScript?

await waits for a Promise to settle and gives you its fulfilled value.

async function getData() {

    const result = await somePromise();

    console.log(result);
}

await can normally be used inside an async function, with top-level await also available in supported JavaScript module environments.

3. What is the difference between Promise .then() and async/await?

Both can work with Promises.

Using .then():

getData()
    .then(function(result) {
        console.log(result);
    });

Using async/await:

async function showData() {

    const result = await getData();

    console.log(result);
}

async/await often makes longer asynchronous code easier to read.

4. How do you handle errors with async/await?

Use try...catch.

async function getData() {

    try {

        const result = await getDataFromServer();

        console.log(result);

    } catch (error) {

        console.log(error);

    }
}

If the awaited Promise rejects, control moves to the catch block.

5. Can an async function return a normal value?

Yes.

async function getNumber() {
    return 10;
}

The function returns a Promise that fulfills with 10.

You can access the value with:

getNumber().then(function(number) {
    console.log(number);
});

6. Can I use await with multiple Promises?

Yes. For independent Promises, Promise.all() is often a good choice.

async function loadData() {

    const results = await Promise.all([
        getUsers(),
        getProducts(),
        getOrders()
    ]);

    console.log(results);
}

The function waits until all three Promises fulfill.

7. Does await stop the entire JavaScript program?

No. await pauses the current async function until the awaited Promise settles. It does not freeze the entire JavaScript runtime or browser page.

For example:

async function example() {

    await somePromise();

    console.log("Finished");

}

example();

console.log("Other code");

The "Other code" statement can execute while the asynchronous operation is pending.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top