Your order ticket
At a momo stall you get a token: "Number 42". It's a promise that you'll get food later — or bad news if they run out. A JavaScript promise is that token for a future value.
Using a promise: then and catch
function orderMomo() {
return new Promise((resolve) => {
setTimeout(() => resolve("Momo ready! 🥟"), 500);
});
}
orderMomo().then((food) => {
console.log(food);
});
console.log("Token received, waiting…");A promise can also fail. Call reject with an error, and handle it with .catch:
function orderMomo(plates) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (plates > 5) reject(new Error("Sorry, not enough momo!"));
else resolve(plates + " plates ready");
}, 300);
});
}
orderMomo(10)
.then((msg) => console.log(msg))
.catch((err) => console.log("Problem: " + err.message));