A Promise is an IOU (I Owe You) for a future value. It prevents the dreaded "Callback Hell" by flattening nested code.
Consuming a Promise
Simulating a coin flip network request.
javascript
const coinFlip = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) resolve("Heads! You win.");
else reject("Tails! You lose.");
}, 1000);
});
console.log("Flipping coin...");
coinFlip
.then(result => console.log("Success:", result))
.catch(err => console.error("Failure:", err))
.finally(() => console.log("Game Over."));Advanced: Parallel Execution
The Chef Analogy
If you need Toast AND Coffee:
Sequential: Make toast (wait 2m). Then make coffee (wait 2m). Total: 4m.
Parallel (Promise.all): Start toast AND start coffee. Wait for both. Total: 2m.
javascript
const getToast = new Promise(r => setTimeout(() => r("Toast"), 1000));
const getCoffee = new Promise(r => setTimeout(() => r("Coffee"), 1000));
console.log("Starting breakfast...");
Promise.all([getToast, getCoffee])
.then(([food, drink]) => {
console.log(`Breakfast is served: ${food} and ${drink}`);
});