0
0
Javascriptprogramming~20 mins

Why promises are used in Javascript - See It in Action

Choose your learning style9 modes available
Understanding Why Promises Are Used in JavaScript
📖 Scenario: Imagine you are ordering a pizza online. You place your order and wait for the pizza to be delivered. Meanwhile, you can do other things like setting the table or watching TV. You don't want to just sit and wait doing nothing. This is similar to how computers handle tasks that take time, like fetching data from the internet.
🎯 Goal: You will create a simple JavaScript program that shows how promises help handle tasks that take time without stopping other work. You will see how promises let your program wait for something to finish and then continue smoothly.
📋 What You'll Learn
Create a promise that simulates waiting for a pizza delivery
Add a variable to hold the message when the pizza is ready
Use the then method to handle the promise result
Print the message when the pizza is delivered
💡 Why This Matters
🌍 Real World
Promises are used in websites and apps to handle things like loading images, fetching data from servers, or waiting for user actions without freezing the screen.
💼 Career
Understanding promises is essential for web developers and anyone working with JavaScript to build fast, user-friendly applications.
Progress0 / 4 steps
1
Create a promise to simulate pizza delivery
Create a variable called pizzaPromise and set it to a new Promise that waits 2 seconds using setTimeout and then resolves with the string 'Pizza is ready!'.
Javascript
Need a hint?

Use new Promise with a function that calls resolve inside setTimeout.

2
Add a variable to hold the delivery message
Create a variable called deliveryMessage and set it to an empty string ''.
Javascript
Need a hint?

Use let deliveryMessage = ''; to create an empty string variable.

3
Use then to handle the promise result
Use pizzaPromise.then with a function that takes a parameter called message and sets deliveryMessage to message.
Javascript
Need a hint?

Use pizzaPromise.then((message) => { deliveryMessage = message; }); to handle the promise.

4
Print the delivery message after the promise resolves
Inside the then function, add a console.log(deliveryMessage) statement to print the message when the pizza is ready.
Javascript
Need a hint?

Use console.log(deliveryMessage); inside the then callback to show the message.