0
0
Javascriptprogramming~20 mins

Why async and await are needed in Javascript - See It in Action

Choose your learning style9 modes available
Why async and await are needed
📖 Scenario: Imagine you want to get some information from the internet, like the weather or news. Sometimes, this takes time. Your program should not stop and wait but keep doing other things. This is where async and await help.
🎯 Goal: You will create a simple program that shows how async and await make it easy to wait for information without stopping everything else.
📋 What You'll Learn
Create a function called getData that returns a promise simulating a delay
Create a variable called message with a string value
Create an async function called showData that uses await to wait for getData
Print the message and the result from getData
💡 Why This Matters
🌍 Real World
Many apps get information from the internet or slow devices. Using <code>async</code> and <code>await</code> helps keep apps smooth and responsive.
💼 Career
Understanding <code>async</code> and <code>await</code> is important for web developers, especially when working with APIs, databases, or any task that takes time.
Progress0 / 4 steps
1
Create a function that simulates waiting for data
Create a function called getData that returns a promise which resolves with the string 'Data received' after 2 seconds.
Javascript
Need a hint?

Use setTimeout inside a Promise to delay the response.

2
Create a message variable
Create a variable called message and set it to the string 'Waiting for data...'.
Javascript
Need a hint?

Use const to create the message variable.

3
Create an async function to wait for data
Create an async function called showData. Inside it, use await with getData() and save the result in a variable called data.
Javascript
Need a hint?

Remember to add async before the function and use await inside it.

4
Print the message and the data
Inside the showData function, add two console.log statements: one to print the message variable, and one to print the data variable. Then call showData().
Javascript
Need a hint?

Print the message first, then the data. Don't forget to call showData().