What is a Promise in JavaScript?
A Promise is an object that represents the future result of an asynchronous operation.
For example, when you request data from an API, JavaScript doesn't want to stop your entire program while waiting for the server. A Promise represents that waiting operation.
Promise has 3 states
1.Pending — operation is still running.
2.Fulfilled — operation completed successfully.
3.Rejected — operation failed.
SIMPLE EXAMPLE:
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data received!");
}else {
reject("Something went wrong!");
}
});
Here:
*resolve() → success
*reject() → failure
You can consume the Promise using .then() and .catch():
promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
OUTPUT:
Data received!
JUST A SIMPLE EXAMPLE:
Imagine you order food 🍕.
When you place the order, the restaurant doesn't immediately give you the food.
The order is:
Pending
↓
Food prepared successfully → Fulfilled
or:
Pending
↓
Restaurant couldn't prepare it → Rejected
The Promise is like the restaurant saying:
"Your food will be ready later."
WHY DO WE NEED PROMISE:
We need Promises in JavaScript because some tasks take time, like getting data from a server. JavaScript can start that task and continue doing other work instead of waiting.
Simple example
Imagine you ask a server for user data:
console.log("Start");
fetch("https://example.com/users")
.then(response => response.json())
.then(data =>{
console.log(data);
});
console.log("End");
The output will be roughly:
Start
End
[user data]
Why?
fetch() takes time. Instead of stopping the program and waiting, JavaScript says:
"I'll give you the data when it's ready."
That's what the Promise represents.
Top comments (0)