Welcome, JavaScript adventurers! In this chapter, we delve into the world of async/await, a powerful syntax that simplifies asynchronous programming in JavaScript. Buckle up as we explore the fundamentals, practical applications, and advanced considerations of using async/await effectively.
async function getUserData(userId) {
// Simulate fetching data from a server (replace with actual fetch API call)
const userData = { name: "Alice", age: 30 };
const delay = Math.random() * 1000; // Simulate random delay
await new Promise(resolve => setTimeout(resolve, delay)); // Wait for the delay
return userData;
}
(async () => {
try {
const data = await getUserData(123);
console.log(data); // Output: { name: "Alice", age: 30 } (after random delay)
} catch (error) {
console.error(error);
}
})();
getUserData function is now declared as async. This allows us to use await inside it.await is used before a promise-based operation (here, a simulated delay using new Promise).await keyword pauses the execution of the async function until the promise settles (resolves or rejects).(async () => { ... })() to ensure proper handling of the returned promise.try...catch blocks.
async function getUserData(userId) {
// Simulate fetching data from a server (replace with actual fetch API call)
try {
const response = await fetch("https://api.example.com/users/" + userId);
if (!response.ok) {
throw new Error("Failed to fetch user data");
}
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
(async () => {
const data = await getUserData(123);
console.log(data);
})();
try...catch block to handle potential errors within the async function.await can be used before both promise-based operations (fetch and JSON parsing).throw and caught in the catch block.
async function getUserNameAndPosts(userId) {
const userData = await getUserData(userId);
const userPosts = await getUserPosts(userData.id);
return { user: userData, posts: userPosts };
}
(async () => {
const data = await getUserNameAndPosts(123);
console.log(data); // Output: { user: ..., posts: [...] } (after delays)
})();
await multiple times within an async function for sequential asynchronous operations.await waits for the previous promise to settle before proceeding.By mastering async/await, you can write cleaner, more readable, and maintainable asynchronous code in JavaScript. It provides a more intuitive way to handle asynchronous operations, improving code flow and error handling. Happy coding !❤️
