JavaScript – Async and Await
Introduction
async and await are modern JavaScript features that make working with asynchronous code simpler, cleaner, and more readable. They are built on top of Promises and are widely used in React applications for API calls, data fetching, and asynchronous operations.
Understanding async and await is essential for writing clean, production-ready JavaScript and React code.
What is Asynchronous JavaScript?
Asynchronous JavaScript allows tasks like API calls, file loading, or timers to run without blocking the main thread.
Examples of asynchronous tasks:
- API requests
- Database calls
- Timers
- File operations
Without async handling, the UI would freeze while waiting for responses.
What is async?
The async keyword is used before a function to make it asynchronous.
Key points:
- An async function always returns a Promise
- You can use
awaitinside an async function - It simplifies Promise-based code
Example
async function getData() {
return "Hello World";
}
This function automatically returns a Promise.
What is await?
The await keyword pauses the execution of an async function until a Promise is resolved or rejected.
Key points:
- await can only be used inside async functions
- It makes asynchronous code look synchronous
- It improves readability
Async/Await vs Promises
Using Promises
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Using Async/Await
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
Async/await is easier to read and maintain.
Basic Async/Await Example
async function fetchMessage() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
}
fetchMessage();
Using Async/Await in React
Async/await is commonly used inside useEffect for API calls.
Example
import { useEffect, useState } from "react";
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
setUsers(data);
};
fetchUsers();
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UsersList;
Error Handling with Try and Catch
Async/await uses try...catch for error handling.
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
} catch (error) {
console.error(error.message);
}
This approach is clean and readable.
Using Finally Block
The finally block runs whether the operation succeeds or fails.
try {
await fetchData();
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
Useful for updating loading states.
Multiple Await Calls
Async/await can handle multiple asynchronous calls.
Sequential Execution
const user = await fetchUser();
const posts = await fetchPosts();
Parallel Execution (Better Performance)
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts(),
]);
Common Mistakes with Async/Await
- Using await outside async functions
- Forgetting try-catch
- Blocking sequential calls unnecessarily
- Ignoring Promise.all for parallel tasks
- Not handling errors properly
Best Practices for Async/Await
- Always use try-catch
- Handle loading and error states
- Prefer Promise.all for parallel calls
- Keep async functions small and readable
- Avoid unnecessary awaits
Async/Await with Axios
Axios works seamlessly with async/await.
const fetchUsers = async () => {
try {
const response = await axios.get(url);
setUsers(response.data);
} catch (error) {
console.error(error);
}
};
Interview Questions and Answers – Async/Await
1. What is async in JavaScript?
async is a keyword that makes a function return a Promise.
2. What is await?
await pauses execution until a Promise resolves.
3. Can await be used outside async?
No, it must be inside an async function.
4. How do you handle errors in async/await?
Using try-catch blocks.
5. Is async/await synchronous?
No, it is asynchronous but looks synchronous.
6. What does an async function return?
Always a Promise.
7. How do you run multiple async calls together?
Using Promise.all.
8. Is async/await better than Promises?
It improves readability but uses Promises internally.
9. Can async/await be used in React?
Yes, commonly used for API calls.
10. Is async/await supported in modern browsers?
Yes, it is widely supported.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
