Async/Await
Topic 6JavaScript Part 2 (Async JS)
Async/Await
Introduction
The async and await keywords simplify handling Promises, allowing asynchronous code to appear synchronous.
Key Concepts and Definitions
async
Makes a function return a Promise.
await
Pauses the execution until the Promise resolves or rejects. Can only be used inside async functions.
Step-by-Step Explanation
How It Works:
- •The await keyword pauses the execution until the Promise resolves or rejects.
- •The try-catch block handles errors gracefully.
Examples
Async/Await Example:
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch failed:', error);
}
}
fetchData();Interview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment