Junior
What is a Promise in JavaScript?
sobes.tech AI
Answer from AI
Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise is in one of three states: pending, fulfilled, or rejected. It allows avoiding "callback hell" and makes asynchronous code more readable and manageable.
Main methods of Promise:
.then(): Handles the successful completion of a Promise and returns a new Promise. It takes a handler function for the successful result..catch(): Handles the rejection of a Promise and returns a new Promise. It takes a handler function for errors. It is syntactic sugar for.then(null, rejectionHandler)..finally(): Executes a function regardless of the Promise's outcome (success or failure). Useful for resource cleanup.Promise.all(iterable): Returns a new Promise that resolves when all Promises in the provided iterable are resolved. It rejects if any of the Promises reject.Promise.race(iterable): Returns a new Promise that resolves or rejects as soon as any of the Promises in the provided iterable resolve or reject.Promise.resolve(value): Returns a Promise that resolves with the specified value.Promise.reject(reason): Returns a Promise that rejects with the specified reason.
Example usage:
// Creating a new Promise
const myPromise = new Promise((resolve, reject) => {
const success = true; // Simulating a successful or unsuccessful operation
if (success) {
setTimeout(() => {
resolve("Operation completed successfully!"); // Call resolve on success
}, 1000);
} else {
setTimeout(() => {
reject("Operation failed!"); // Call reject on failure
}, 1000);
}
});
// Using the Promise
myPromise
.then((result) => {
// This block executes on successful Promise resolution
console.log(result);
return "Processed!"; // Returning a value for the next .then
})
.then((nextResult) => {
// This block executes after the previous .then
console.log(nextResult);
})
.catch((error) => {
// This block executes if the Promise is rejected
console.error(error);
})
.finally(() => {
// This block executes always, regardless of the outcome
console.log("Promise completed.");
});