What is a Promise?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Think of it as a "promise" to deliver a result at some future time.
Key States of a Promise
A promise can be in one of three states:
- Pending: The initial state. The promise is neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
. Basic Structure
Here's the basic structure of creating a promise:
let myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
if (/* operation successful */) {
resolve('Success!');
} else {
reject('Failure!');
}
});
Using Promises
You use .then() to handle a fulfilled promise and .catch() to handle a rejected promise.
myPromise
.then(result => {
console.log(result); // 'Success!'
})
.catch(error => {
console.log(error); // 'Failure!'
});
Funny Example: Ordering Pizza
Imagine you're ordering a pizza. You call the pizzeria (async operation), and they promise to deliver the pizza (Promise).
let orderPizza = new Promise((resolve, reject) => {
let pizzaReady = true; // Change to false to simulate a failure
console.log("Ordering pizza...");
setTimeout(() => {
if (pizzaReady) {
resolve("Pizza is here!");
} else {
reject("Sorry, we ran out of dough.");
}
}, 2000); // Simulate a 2-second wait for pizza
});
orderPizza
.then(message => {
console.log(message); // "Pizza is here!"
})
.catch(error => {
console.log(error); // "Sorry, we ran out of dough."
});
Chaining Promises
You can chain multiple .then() calls. Each .then() returns a new promise.
orderPizza
.then(message => {
console.log(message); // "Pizza is here!"
return "Enjoy your pizza!";
})
.then(message => {
console.log(message); // "Enjoy your pizza!"
})
.catch(error => {
console.log(error); // "Sorry, we ran out of dough."
});
Top comments (0)