Async/Await in JavaScript is a modern syntax for handling asynchronous operations, introduced in ES2017 (also known as ES8). It simplifies working with promises, making asynchronous code easier to read and maintain by using a more synchronous-looking structure.
How Async/Await Works
Async Functions: An async function is a function declared with the async keyword. It always returns a promise, and within it, you can use the await keyword.
async function greetings() {
return "Hello, Async!";
}
greetings().then(console.log); // Output: "Hello, Async!"
Await Keyword: The await keyword pauses the execution of the async function until the promise it is waiting for resolves. It can only be used inside async functions.
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
fetchData();
Advantages
Improved Readability: Code written with async/await is more linear and easier to understand compared to nested .then() chains.
Error Handling: Errors can be handled more cleanly using try/catch blocks.
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
Works Well with Promises: Async/await is built on top of promises, so it integrates seamlessly with existing promise-based APIs.
When to Use Async/Await
Use async/await for scenarios involving:
- Fetching data from APIs.
- Sequential asynchronous operations.
- Readable and maintainable code for complex async flows.
JavaScript Async/Await – Interview Questions
Q 1: What is async/await?
Ans: Syntax to handle promises easily.
Q 2: What does async return?
Ans: Always returns a promise.
Q 3: What does await do?
Ans: Pauses execution until the promise resolves.
Q 4: Can await be used without async?
Ans: No.
Q 5: Why use async/await?
Ans: Improves readability.
JavaScript Async/Await – Objective Questions (MCQs)
Q1. Which keyword is used to declare an async function?
Q2. The await keyword can be used only inside ______.
Q3. What does an async function always return?
Q4. await pauses execution until the Promise is ______.
Q5. Async/Await is built on top of ______.