Lesson 25 - Async/Await in JavaScript
Async/Await is a modern way to handle asynchronous operations in JavaScript. It makes asynchronous code look and behave more like synchronous code, improving readability.
Example 1: Using async and await with a Promise
async function fetchData() {
return "Data received!";
}
fetchData().then(result => console.log(result)); // Output: Data received!
- The function
fetchDataautomatically returns a Promise.
Explanation
- The
asynckeyword is used to declare an asynchronous function. - The
awaitkeyword pauses the execution of anasyncfunction until the Promise resolves or rejects. awaitcan only be used inside anasyncfunction.
Example 2: Awaiting a Promise
function getUser() {
return new Promise(resolve => {
setTimeout(() => resolve({ name: "Alice", age: 25 }), 2000);
});
}
async function showUser() {
let user = await getUser();
console.log(`User: ${user.name}, Age: ${user.age}`);
}
showUser();
- The function
showUser()waits forgetUser()to complete before logging the result.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson25-async-await.html.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 25 - Async/Await</title> </head> <body> <script> function fetchData() { return new Promise(resolve => { setTimeout(() => resolve("Hello, Async/Await!"), 1500); }); } async function displayMessage() { let message = await fetchData(); console.log(message); } displayMessage(); </script> </body> </html>
-
-
Save the File.
-
Preview in Browser and Check Console Output.
Experiment
- Modify
getUser()to reject if no user is found and handle it withtry...catch. - Create an
asyncfunction that fetches and logs two pieces of data in sequence.
Key Takeaways
asyncfunctions return a Promise.awaitpauses execution until the Promise resolves.try...catchcan be used to handle errors inasyncfunctions.