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
fetchData
automatically returns a Promise.
Explanation
- The
async
keyword is used to declare an asynchronous function. - The
await
keyword pauses the execution of anasync
function until the Promise resolves or rejects. await
can only be used inside anasync
function.
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
async
function that fetches and logs two pieces of data in sequence.
Key Takeaways
async
functions return a Promise.await
pauses execution until the Promise resolves.try...catch
can be used to handle errors inasync
functions.