Promises help you handle tasks that take time, like loading data. They let your program wait for the task to finish without stopping everything.
Creating promises in Javascript
Introduction
Syntax
Javascript
const myPromise = new Promise((resolve, reject) => { // do something asynchronous const success = true; // example condition if (success) { resolve(result); // task finished successfully } else { reject(error); // task failed } });
resolve is called when the task finishes well.
reject is called when the task fails.
Examples
Javascript
const promise = new Promise((resolve, reject) => { resolve('Done!'); });
Javascript
const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Waited 1 second'); }, 1000); });
error is true.Javascript
const promise = new Promise((resolve, reject) => { const error = true; if (error) { reject('Something went wrong'); } else { resolve('All good'); } });
Sample Program
This program creates a promise that finishes successfully. It then prints the success message.
Javascript
const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('Task completed successfully'); } else { reject('Task failed'); } }); myPromise .then(message => { console.log('Success:', message); }) .catch(error => { console.log('Error:', error); });
Important Notes
Promises always run the code inside immediately when created.
Use then to handle success and catch to handle errors.
Promises help keep your program responsive by not blocking other code.
Summary
Promises represent tasks that finish later with success or failure.
You create a promise with new Promise((resolve, reject) => { ... }).
Call resolve when done well, reject when there is an error.
Practice
1. What does the
resolve function do inside a JavaScript Promise?easy
Solution
Step 1: Understand the role of
Theresolvein promisesresolvefunction is called when the asynchronous task finishes successfully.Step 2: Differentiate from
rejectrejectis used for failure, soresolvemust mean success.Final Answer:
It marks the promise as successfully completed. -> Option CQuick Check:
resolve = success [OK]
Hint: Resolve means success, reject means failure [OK]
Common Mistakes:
- Confusing resolve with reject
- Thinking resolve cancels the promise
- Believing resolve pauses execution
2. Which of the following is the correct syntax to create a new Promise in JavaScript?
easy
Solution
Step 1: Recall the Promise constructor syntax
The Promise constructor takes a single function with two parameters: resolve and reject, wrapped in parentheses.Step 2: Check each option for correct syntax
new Promise((resolve, reject) => { }) correctly usesnew Promise((resolve, reject) => { }). Others have syntax errors.Final Answer:
new Promise((resolve, reject) => { }) -> Option DQuick Check:
Promise syntax = new Promise((resolve, reject) => { }) [OK]
Hint: Promise needs a function with (resolve, reject) inside parentheses [OK]
Common Mistakes:
- Missing parentheses around parameters
- Using wrong keyword order
- Incorrect arrow function syntax
3. What will be the output of this code?
const p = new Promise((resolve, reject) => {
resolve('Done');
});
p.then(result => console.log(result));medium
Solution
Step 1: Understand promise resolution
The promise callsresolve('Done'), so it completes successfully with value 'Done'.Step 2: Check what
thendoesthenreceives the resolved value and logs it, so 'Done' is printed.Final Answer:
Done -> Option AQuick Check:
Resolved value logged = Done [OK]
Hint: Resolve value appears in then callback [OK]
Common Mistakes:
- Expecting undefined instead of resolved value
- Confusing promise object with resolved output
- Thinking promise logs automatically
4. Find the error in this Promise creation code:
const p = new Promise(resolve, reject) => {
resolve('Success');
};medium
Solution
Step 1: Check Promise constructor usage
The Promise constructor requires a single function argument wrapped in parentheses.Step 2: Identify arrow function syntax error
The code usesnew Promise(resolve, reject) => { }which is invalid syntax. It should benew Promise((resolve, reject) => { }).Final Answer:
Arrow function syntax is incorrect for Promise constructor. -> Option BQuick Check:
Arrow function must be inside parentheses [OK]
Hint: Promise needs one function argument wrapped in parentheses [OK]
Common Mistakes:
- Not wrapping parameters in parentheses
- Omitting new keyword (not in this case)
- Using wrong arrow function syntax
5. You want to create a Promise that waits 1 second and then resolves with 'Done'. Which code correctly does this?
hard
Solution
Step 1: Understand how to delay resolution
UsesetTimeoutto delay callingresolveby 1000 ms (1 second).Step 2: Check each option for correct usage
new Promise((resolve) => { setTimeout(() => resolve('Done'), 1000); }) correctly passes a function to Promise and callsresolve('Done')insidesetTimeout. new Promise(resolve => setTimeout(resolve('Done'), 1000)) calls resolve immediately. new Promise((resolve, reject) => { resolve('Done'); setTimeout(() => {}, 1000); }) resolves immediately and delays nothing. new Promise(() => { setTimeout(() => resolve('Done'), 1000); }) does not receive resolve parameter.Final Answer:
new Promise((resolve) => { setTimeout(() => resolve('Done'), 1000); }) -> Option AQuick Check:
Delay resolve with setTimeout inside Promise [OK]
Hint: Wrap resolve call inside setTimeout function [OK]
Common Mistakes:
- Calling resolve immediately instead of inside setTimeout
- Not passing resolve parameter
- Placing setTimeout outside Promise
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
