A Promise in JavaScript is an object that represents a value that you don’t have yet, but will get in the future.
It’s mainly used for asynchronous operations like fetching data from an API, reading a file, or waiting for a timer.
A Promise has three possible states:
Pending – the work is still happening.
Fulfilled – the work is done successfully.
Rejected – the work failed.
Promises help you avoid callback hell and write cleaner asynchronous code.
Example:
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation completed successfully!");
} else {
reject("Something went wrong.");
}
});
myPromise
.then(result => {
console.log(result); // Output: Operation completed successfully!
})
.catch(error => {
console.log(error); // Output: Something went wrong.
});
What happens here?
resolve() means the promise succeeded
reject() means it failed
then() runs when it succeeds
catch() runs when it fails
Top comments (0)