0
0
Javascriptprogramming~15 mins

Creating promises in Javascript - Try It Yourself

Choose your learning style9 modes available
Creating promises
📖 Scenario: You are building a simple app that simulates checking if a user is logged in. This check takes some time, so you will use a promise to handle the waiting.
🎯 Goal: Create a promise that waits 2 seconds and then resolves with the message "User is logged in". Then display this message.
📋 What You'll Learn
Create a promise called loginCheck that waits 2 seconds before resolving
Use setTimeout inside the promise executor function
Resolve the promise with the exact string 'User is logged in'
Use loginCheck.then to get the resolved message
Print the resolved message using console.log
💡 Why This Matters
🌍 Real World
Promises are used in web apps to handle tasks like loading data from servers, waiting for user input, or running animations smoothly.
💼 Career
Understanding promises is essential for frontend and backend JavaScript developers to write clean, readable, and efficient asynchronous code.
Progress0 / 4 steps
1
Create the loginCheck promise
Create a promise called loginCheck using new Promise with an executor function that takes resolve and reject as parameters.
Javascript
Need a hint?

Use new Promise((resolve, reject) => { }) to create the promise.

2
Add a 2-second delay and resolve the promise
Inside the loginCheck promise executor, use setTimeout to wait 2000 milliseconds, then call resolve with the string 'User is logged in'.
Javascript
Need a hint?

Use setTimeout(() => { resolve('User is logged in'); }, 2000) inside the promise.

3
Use then to get the resolved message
Use loginCheck.then with a function that takes a parameter message and inside it, call console.log(message).
Javascript
Need a hint?

Use loginCheck.then(message => console.log(message)) to print the message.

4
Print the resolved message
Run the program and observe that after 2 seconds, the console prints User is logged in.
Javascript
Need a hint?

Wait 2 seconds after running to see the message printed in the console.