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
- The
asynckeyword makesshowMessage()an asynchronous function. - An
asyncfunction always returns a Promise. - The string is automatically wrapped in a fulfilled Promise.
.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
getMessage()returns a Promise.- The Promise waits for approximately 2 seconds.
resolve()sends the result.awaitwaits for that Promise to settle.- The result is stored in
message. - 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
getNumber()returns a fulfilled Promise.awaitgets the value10.- The value is stored in
number. number * 2gives20.- 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
getData()returns a rejected Promise.awaitencounters the rejection.- JavaScript moves to the
catchblock. - The error is stored in
error. - 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
waitThreeSeconds()creates a Promise.setTimeout()waits approximately 3 seconds.- The Promise resolves after the delay.
awaitwaits for the result."Finished!"is stored inmessage.- 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
square()is an async function.- It calculates
6 * 6. - The result is
36. - Because the function is
async, the result is returned through a Promise. .then()receives36.
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
getUserName()returns a Promise.awaitwaits for the username.getCourse()returns another Promise.- The second
awaitwaits for the course. - 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
- Three functions return Promises.
- All three Promises are passed to
Promise.all(). awaitwaits until all of them fulfill.- The results are returned as an array.
- 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
getStudent()returns a Promise.- The Promise simulates a delayed operation.
- After approximately 2 seconds, it resolves with an object.
awaitwaits for the object.- The object is stored in
student. - 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
login()returns a Promise.setTimeout()simulates a delayed login request.- The username and password are checked.
- Correct credentials call
resolve(). - Incorrect credentials call
reject(). awaitwaits for the Promise.- Successful results are handled normally.
- Rejected Promises move execution to
catch. error.messagedisplays the reason for failure.
This pattern is very useful when working with real asynchronous operations such as API requests.
Key Takeaways
asyncis used to create an asynchronous function.- An
asyncfunction always returns a Promise. awaitis used inside an async function to wait for a Promise’s result.awaitmakes asynchronous code easier to read.try...catchis commonly used withasync/awaitfor error handling.async/awaitdoes not remove the asynchronous nature of JavaScript.Promise.all()can be combined withawait.- Multiple independent operations can often be started together with
Promise.all(). awaitpauses 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.
awaitcan be used with any Promise-like value.async/awaitis 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.
