Imagine that you ordered coffee at a café. The barista takes the order, gives you a receipt, and says, “Please wait a moment.” You don’t stand still; you can go sit at a table, check your phone, or respond to messages. When the coffee is ready, the barista calls you – and you get the result.
Promise in JavaScript works the same way:
You make a request (for example, to a server) and receive a promise that the response will come later.
JavaScript does not stop executing code – it continues to perform other tasks.
When the result is ready, the Promise notifies you, and you can handle it.
A Simple Example of Promise
function makeCoffee() {
return new Promise((resolve) => {
console.log("Order received...");
setTimeout(() => {
resolve("☕ Ready! Here is your coffee.");
}, 2000);
});
}
console.log("I am scrolling through my phone...");
makeCoffee().then((message) => console.log(message));
First, console.log("I am scrolling through my phone...") will execute because the promise does not block the code.
Then, after 2 seconds, "☕ Ready! Here is your coffee." will appear when the promise is fulfilled.
If something goes wrong (for example, if the coffee runs out), we can add .catch():
function makeCoffee() {
return new Promise((resolve, reject) => {
const coffeeReady = Math.random() > 0.5; // random success or failure
console.log("Order received...");
setTimeout(() => {
if (coffeeReady) {
resolve("☕ Ready! Here is your coffee.");
} else {
reject("❌ Sorry, the coffee has run out.");
}
}, 2000);
});
}
makeCoffee()
.then((message) => console.log(message))
.catch((error) => console.log(error));
This is like real life: if there is no coffee, the barista apologizes, and you receive an error response.
How to Quickly Understand?
Try writing promises on your own: create a function that waits 3 seconds before responding, or one that randomly fails. This way, you can quickly understand how asynchronous code works.
But before you start experimenting with promises, you need to understand the structure (resolve, reject, catch, etc.). There is a separate post on this.