Promise
A Promise in JavaScript is an object that represents the eventual completion (success) or failure of an asynchronous operation and its resulting value.
A Promise has three states:
- Pending – the operation is still going on.
- Fulfilled – the operation completed successfully (resolve).
- Rejected – the operation failed (reject).
Example :
let promise = new Promise((resolve, reject) => {
// Do some task (like fetching data)
let success = true;
if (success) {
resolve("Task completed successfully!");
} else {
reject("Task failed!");
}
});
// Using .then() and .catch()
promise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Error:", error);
});
Example :
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let dataFetched = true;
if (dataFetched) {
resolve("Data received!");
} else {
reject("Failed to fetch data.");
}
}, 2000);
});
}
getData()
.then(response => console.log(response)) // Success
.catch(error => console.log(error)); // Failure
Promise Methods :
- - .then() → runs when promise is resolved.
- - .catch() → runs when promise is rejected.
- - .finally() → runs always (success or failure).
- - Promise.all([p1, p2, ...]) → waits for all promises.
- - Promise.race([p1, p2, ...]) → returns the first settled promise.
Top comments (0)