Introductions
JavaScript Promises are used to handle operations that finish later, such as fetching data from an API, reading files, or waiting for another asynchronous task. A Promise can be pending, fulfilled, or rejected. In this chapter, you will practice creating Promises, using .then(), .catch(), .finally(), handling success and failure, and working with multiple Promises. JavaScript Promises practice questions with solutions help to understand the concepts.
Question 1: Create a Simple Promise
Problem
Create a Promise that successfully returns the message "Task completed!".
Solution
const promise = new Promise(function(resolve, reject) {
resolve("Task completed!");
});
console.log(promise);
Output
The console shows a fulfilled Promise containing:
Task completed!
Step-by-step Explanation
new Promise()creates a Promise.- A Promise receives a function containing
resolveandreject. resolve()marks the Promise as successfully completed.- The message is passed to the Promise.
- The Promise changes from pending to fulfilled.
The basic structure is:
const promise = new Promise(function(resolve, reject) {
// asynchronous operation
});
Question 2: Handle a Successful Promise with .then()
Problem
Create a Promise and use .then() to display its successful result.
Solution
const promise = new Promise(function(resolve, reject) {
resolve("Data received successfully.");
});
promise.then(function(result) {
console.log(result);
});
Output
Data received successfully.
Step-by-step Explanation
- The Promise is created.
resolve()sends the success value..then()receives the resolved value.- The value is stored in
result. - The message is displayed.
.then() is commonly used when you want to perform an action after a Promise succeeds.
Question 3: Handle a Rejected Promise with .catch()
Problem
Create a Promise that fails and use .catch() to handle the error.
Solution
const promise = new Promise(function(resolve, reject) {
reject("Something went wrong.");
});
promise.catch(function(error) {
console.log(error);
});
Output
Something went wrong.
Step-by-step Explanation
- The Promise starts in the pending state.
reject()marks the Promise as failed..catch()handles the rejected value.- The error message is displayed.
A common pattern is:
promise
.then(function(result) {
// success
})
.catch(function(error) {
// failure
});
Question 4: Create a Delayed Promise
Problem
Create a Promise that resolves after 2 seconds.
Solution
const promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Promise completed!");
}, 2000);
});
promise.then(function(result) {
console.log(result);
});
Output
After approximately 2 seconds:
Promise completed!
Step-by-step Explanation
- A Promise is created.
setTimeout()waits for approximately 2 seconds.resolve()is called after the delay.- The Promise becomes fulfilled.
.then()receives the result.- The result is displayed.
This is a simple example of combining Promises and timers.
Question 5: Handle Both Success and Failure
Problem
Create a Promise that checks a number. Resolve it if the number is positive and reject it if the number is zero or negative.
Solution
function checkNumber(number) {
return new Promise(function(resolve, reject) {
if (number > 0) {
resolve("Number is positive.");
} else {
reject("Number must be positive.");
}
});
}
checkNumber(10)
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error);
});
Output
Number is positive.
If you call:
checkNumber(-5)
The output becomes:
Number must be positive.
Step-by-step Explanation
checkNumber()returns a Promise.- The number is checked.
- A positive number calls
resolve(). - Zero or a negative number calls
reject(). .then()handles success..catch()handles failure.
Question 6: Use .finally()
Problem
Create a Promise and use .finally() to display a message after the Promise has finished.
Solution
const promise = new Promise(function(resolve, reject) {
resolve("Download completed.");
});
promise
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error);
})
.finally(function() {
console.log("Process finished.");
});
Output
Download completed.
Process finished.
Step-by-step Explanation
- The Promise resolves successfully.
.then()handles the result..finally()runs after the Promise settles.finally()runs whether the Promise is fulfilled or rejected.
It is useful for cleanup or completion tasks.
Question 7: Chain Multiple .then() Methods
Problem
Create a Promise that returns a number. Double the number in the first .then() and add 10 in the second .then().
Solution
const promise = Promise.resolve(5);
promise
.then(function(number) {
return number * 2;
})
.then(function(number) {
return number + 10;
})
.then(function(result) {
console.log(result);
});
Output
20
Step-by-step Explanation
The Promise starts with:
5
First .then():
5 × 2 = 10
Second .then():
10 + 10 = 20
Final output:
20
Each .then() can return a new value that is passed to the next .then().
Question 8: Create a Promise-Based Login Check
Problem
Create a simple login function. If the username is "admin" and password is "1234", resolve the Promise. Otherwise, reject it.
Solution
function login(username, password) {
return new Promise(function(resolve, reject) {
if (username === "admin" && password === "1234") {
resolve("Login successful!");
} else {
reject("Invalid username or password.");
}
});
}
login("admin", "1234")
.then(function(message) {
console.log(message);
})
.catch(function(error) {
console.log(error);
});
Output
Login successful!
If the credentials are incorrect:
Invalid username or password.
Step-by-step Explanation
login()returns a Promise.- The username and password are checked.
- If both values match,
resolve()runs. - Otherwise,
reject()runs. .then()handles successful login..catch()handles failed login.
This example demonstrates how Promises can represent the result of an operation.
Question 9: Run Multiple Promises with Promise.all()
Problem
Create three Promises and use Promise.all() to get all their successful results.
Solution
const promise1 = Promise.resolve("HTML");
const promise2 = Promise.resolve("CSS");
const promise3 = Promise.resolve("JavaScript");
Promise.all([
promise1,
promise2,
promise3
])
.then(function(results) {
console.log(results);
});
Output
[
"HTML",
"CSS",
"JavaScript"
]
Step-by-step Explanation
- Three Promises are created.
- All three are passed to
Promise.all(). Promise.all()waits for all of them to fulfill.- The results are returned as an array.
.then()receives that array.
Promise.all() is useful when several asynchronous operations must all succeed before continuing.
Question 10: Build a Realistic Promise-Based Data Loader
Problem
Create a simulated data-loading function that waits for 2 seconds and then returns user data. Handle both success and failure.
Solution
function loadUser() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
const success = true;
if (success) {
resolve({
name: "Rahul",
age: 20
});
} else {
reject("Unable to load user data.");
}
}, 2000);
});
}
console.log("Loading user...");
loadUser()
.then(function(user) {
console.log("Name:", user.name);
console.log("Age:", user.age);
})
.catch(function(error) {
console.log(error);
})
.finally(function() {
console.log("Loading finished.");
});
Output
Immediately:
Loading user...
After approximately 2 seconds:
Name: Rahul
Age: 20
Loading finished.
Step-by-step Explanation
loadUser()returns a Promise.setTimeout()simulates a delayed operation.- The
successvariable determines whether the operation succeeds. - If successful,
resolve()returns a user object. .then()receives that object.- The user’s name and age are displayed.
- If the operation fails,
.catch()handles the error. .finally()runs after either success or failure.
This pattern is similar to how asynchronous data operations are handled in real applications.
Key Takeaways
- A Promise represents the eventual result of an asynchronous operation.
- A Promise can be pending, fulfilled, or rejected.
resolve()fulfills a Promise.reject()rejects a Promise..then()handles a fulfilled Promise..catch()handles a rejected Promise..finally()runs after the Promise settles.- Promises can be chained.
- A
.then()callback can return a value for the next.then(). Promise.all()can wait for multiple Promises.- Promises are commonly used with APIs and asynchronous operations.
- A Promise settles only once: after it is fulfilled or rejected, later attempts to settle it do not change its state.
- Promise callbacks are handled asynchronously by JavaScript.
FAQs
1. What is a Promise in JavaScript?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
A Promise has three main states:
Pending
↓
Fulfilled
or:
Pending
↓
Rejected
2. What is the difference between resolve() and reject()?
resolve() indicates successful completion:
resolve("Success");
reject() indicates failure:
reject("Failed");
The result can then be handled with .then() or .catch().
3. What does .then() do?
.then() handles the successful result of a Promise.
promise.then(function(result) {
console.log(result);
});
It can also return a value or another Promise for the next step in a chain.
4. What does .catch() do?
.catch() handles a rejected Promise or an error thrown during the preceding Promise chain.
promise.catch(function(error) {
console.log(error);
});
It is commonly used for error handling in asynchronous code.
5. What does .finally() do?
.finally() runs after a Promise has settled, regardless of whether it was fulfilled or rejected.
promise.finally(function() {
console.log("Finished");
});
It is useful for cleanup or completion-related tasks.
6. What is Promise chaining?
Promise chaining means using multiple .then() calls where the result of one step is passed to the next.
Promise.resolve(5)
.then(function(number) {
return number * 2;
})
.then(function(number) {
return number + 5;
})
.then(function(result) {
console.log(result);
});
Output:
15
7. What is Promise.all()?
Promise.all() waits for multiple Promises to fulfill.
Promise.all([
promise1,
promise2,
promise3
])
.then(function(results) {
console.log(results);
});
If all Promises fulfill, the results are returned in an array. If any Promise rejects, the Promise.all() result rejects.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
