0
0
Javascriptprogramming~15 mins

Await keyword behavior in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Await Keyword Behavior
📖 Scenario: Imagine you are building a simple web app that fetches user data from a server. You want to learn how to wait for the data to arrive before using it.
🎯 Goal: You will create a function that simulates fetching data asynchronously and use the await keyword to wait for the data before printing it.
📋 What You'll Learn
Create an asynchronous function called fetchUserData that returns a promise resolving to the string 'User data loaded' after 1 second.
Create an asynchronous function called showUserData.
Inside showUserData, use await to wait for fetchUserData to complete and store the result in a variable called data.
Print the value of data using console.log.
💡 Why This Matters
🌍 Real World
Waiting for data from servers or APIs is common in web apps. Using <code>await</code> helps write clear code that waits for data before continuing.
💼 Career
Understanding <code>async</code> and <code>await</code> is essential for frontend and backend developers working with asynchronous data fetching.
Progress0 / 4 steps
1
Create the asynchronous function fetchUserData
Write an asynchronous function called fetchUserData that returns a promise which resolves to the string 'User data loaded' after 1 second using setTimeout.
Javascript
Need a hint?

Use new Promise inside the async function and setTimeout to delay the resolve by 1000 milliseconds.

2
Create the asynchronous function showUserData
Write an asynchronous function called showUserData that will later use await to get data.
Javascript
Need a hint?

Just create the function with the async keyword and empty body for now.

3
Use await inside showUserData to get data
Inside the showUserData function, use await to wait for fetchUserData() and store the result in a variable called data.
Javascript
Need a hint?

Use const data = await fetchUserData(); inside the function body.

4
Print the awaited data using console.log
Add a line inside showUserData to print the variable data using console.log. Then call showUserData() to run the code.
Javascript
Need a hint?

Use console.log(data); inside showUserData and call showUserData(); after the function.