Problem Statement
Explain async await in JavaScript. How does it make asynchronous code easier to write?
Explanation
Async await is a modern syntax for handling asynchronous operations in JavaScript, built on top of Promises.
The async keyword:
Declare a function as async to make it always return a Promise. If the function returns a value, it is wrapped in a resolved Promise. If it throws an error, it returns a rejected Promise.
The await keyword:
Can only be used inside async functions. Pauses execution until the Promise resolves. Returns the resolved value. If Promise rejects, throws an error.
How it makes code easier:
Looks like synchronous code, easier to read. No need for then chains. Can use try catch for error handling. Can use regular loops and conditionals. Easier to debug than Promise chains.
Error handling:
Use try catch blocks around await statements. Can catch errors from multiple awaits in one catch block. Finally block for cleanup code.
Parallel execution:
Awaiting in sequence is slower. Use Promise all for parallel execution. Destructure results from Promise all.
Code Solution
SolutionRead Only
// Basic async await
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
// Calling async function
fetchData()
.then(data => console.log(data))
.catch(error => console.log(error));
// Or with await (inside another async function)
async function main() {
const data = await fetchData();
console.log(data);
}
// Error handling with try catch
async function getUserData(id) {
try {
const user = await fetchUser(id);
const posts = await fetchPosts(user.id);
const comments = await fetchComments(posts[0].id);
return {user, posts, comments};
} catch (error) {
console.log('Error:', error.message);
return null;
} finally {
console.log('Cleanup');
}
}
// Sequential vs Parallel
// Sequential (slow - takes 6 seconds)
async function sequential() {
const user = await fetchUser(); // 2 seconds
const posts = await fetchPosts(); // 2 seconds
const comments = await fetchComments(); // 2 seconds
return {user, posts, comments};
}
// Parallel (fast - takes 2 seconds)
async function parallel() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
]);
return {user, posts, comments};
}
// Using async await with loops
async function processItems(items) {
for (const item of items) {
await processItem(item); // Sequential
}
}
// Parallel processing with Promise.all
async function processItemsParallel(items) {
await Promise.all(
items.map(item => processItem(item))
);
}
// Compare with Promises
// Promise way:
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => console.log(posts))
.catch(error => console.log(error));
// Async await way:
async function getAndLogPosts() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
console.log(posts);
} catch (error) {
console.log(error);
}
}