What is async
/await
and how does it work?
In the previous lecture videos, you learned about asynchronous programming which allows other code to run while we wait for some time-consuming tasks to complete, like fetching data from a server, reading data from a file, and so on.
async
/await
, built on top of promises, makes writing and reading asynchronous code easier. When you put the async
keyword before a function, it means that function will always return a Promise
. Only inside an async
function, you can use the await
keyword, which allows you to wait for a Promise
to resolve before moving on to the next line of code. Here’s an example to illustrate how async
/await
works:
async function delayedGreeting(name) {
console.log("A Messenger entered the chat...");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log(`Hello, ${name}!`);
}
delayedGreeting("Alice");
console.log("First Printed Message!");
In this code, we define an async
function called delayedGreeting
. Inside this function, we use await
to pause the execution for 2 seconds. After the delay, it prints a greeting.
When we call this function, you’ll see First Printed Message!
appear before the greeting. This is because the function is asynchronous - it doesn’t block the rest of the code from running.
One of the biggest advantages of async
/await
is error handling. With promises, we often had to use .catch()
method to handle errors. With async
/await
, we can use try
/catch
blocks. Here’s an example:
async function fetchUserData() {
try {
let response = await fetch(`https://api.example.com/users`);
let userData = await response.json();
console.log(userData);
} catch (error) {
console.log("Error fetching user data:", error);
}
}
fetchUserData();
In this example, we’re using async
/await
to fetch user data from an API. The await
keyword is used twice: once to wait for the fetch operation to complete, and again to wait for the JSON parsing to finish. If any error occurs during this process, it will be caught in the catch
block.