Q1. What is a Promise in JavaScript?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
It is done in 3 states
Example
It is done in 3 states
- Pending
- Fulfilled (Success)
- Rejected (Failure)
let promise = new Promise(function(resolve, reject) { let success = true;
if(success) { resolve("Task Completed"); } else { reject("Task Failed"); }});
promise .then(function(result) { console.log(result); }) .catch(function(error) { console.log(error); });Q2. What are resolve() and reject()?
resolve() – Used when operation is successful
reject() – Used when operation fails
Example
reject() – Used when operation fails
Example
new Promise(function(resolve, reject) { resolve("Success");});Q3. What is .then() in Promises?
.then() is used to handle successful Promise results.
Example
.then() runs only when Promise is fulfilled.
Example
promise.then(function(result) { console.log(result);});.then() runs only when Promise is fulfilled.
Q4. What is .catch() in Promises?
.catch() handles errors when Promise is rejected.
Example
Helps in proper error handling.
Example
promise.catch(function(error) { console.log(error);});Helps in proper error handling.
Q5. What is promise chaining?
Promise chaining means executing multiple asynchronous tasks one after another using .then().
Each .then() receives result from previous step.
Each .then() receives result from previous step.
