4 min read
•Question 6 of 50mediumWhat is async/await in JavaScript?
Understanding async/await syntax for Promises.
What You'll Learn
- async/await syntax
- Error handling
- Best practices
What is async/await?
async/await is syntactic sugar over Promises that makes asynchronous code look synchronous.
Basic Syntax
code.jsJavaScript
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}Key Points
asyncfunctions always return a Promiseawaitpauses execution until Promise resolves- Use
try/catchfor error handling
Parallel Execution
code.jsJavaScript
// Sequential (slower)
const a = await fetchA();
const b = await fetchB();
// Parallel (faster)
const [a, b] = await Promise.all([fetchA(), fetchB()]);Arrow Function Syntax
code.jsJavaScript
const fetchUser = async (id) => {
const response = await fetch(`/users/${id}`);
return response.json();
};