Chapter XVII · Promises
Promises
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
01 How It Works
Think of ordering a custom item receipt ticket: you hold a promise stub until the item is ready for pickup.
Promises replace messy nested callback pyramids with clean, chainable asynchronous interfaces.
example.js
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
promise.then(result => console.log(result));
1. Instantiate a Promise with an executor function (resolve, reject).
2. Perform async work inside executor.
3. Call resolve(value) on success or reject(error) on failure.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
const checkStock = new Promise((resolve, reject) => {
let inStock = true;
inStock ? resolve("Item available") : reject("Out of stock");
});
Key Takeaway
Promises provide robust syntax and state tracking for asynchronous operations.