JavaScript promises are a feature in the language used to handle asynchronous operations more effectively and avoid callback hell (nested callbacks). A promise represents a value that may be available now, in the future, or never. It acts as a placeholder for a result that will be returned later, allowing you to write cleaner and more manageable asynchronous code.
States of a Promise
1. Pending: The initial state; the promise is neither fulfilled nor rejected.
2. Fulfilled: The operation is completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure (an error).
Using Promises
A promise is created using the promise constructor:
let promise = new Promise((resolve, reject) => {
// Perform an operation
let success = true; // Example condition
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
You can handle the resolved or rejected outcomes using .then() and .catch():
promise.then((result) => {
console.log(result); // "Operation was successful!"
}).catch((error) => {
console.error(error); // "Operation failed."
});
Chaining Promises
Promises can be chained to handle sequences of asynchronous operations:
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
JavaScript Promises – Interview Questions
Q 1: What is a Promise?
Ans: An object representing future completion or failure.
Q 2: Promise states?
Ans: Pending, Fulfilled, Rejected.
Q 3: Which method handles success?
Ans: .then().
Q 4: Which method handles error?
Ans: .catch().
Q 5: What is .finally()?
Ans: Executes regardless of result.
JavaScript Promises – Objective Questions (MCQs)
Q1. Promise represents a value that is ______.
Q2. Which states can a Promise have?
Q3. Which method handles successful Promise results?
Q4. Which method handles Promise errors?
Q5. Which method executes regardless of Promise result?