A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
It has three states:
- Pending → initial state, not resolved or rejected.
- Fulfilled → operation completed successfully.
- Rejected → operation failed.
⚡ Simple Promise Example (Resolves after 1 second)
const waitOneSecond = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done after 1 second");
}, 1000);
});
waitOneSecond.then((message) => {
console.log(message);
});
Output (after 1 second):
Done after 1 second
💡 Explanation:
new Promise()takes a function withresolveandreject.resolve()→ marks the promise as fulfilled.reject()→ marks it as failed..then()is used to handle the fulfilled value..catch()can handle errors if rejected.
✅ In Short:
A Promise is a way to handle async operations in JavaScript without getting into “callback hell.”
Example usage: API calls, timers, or any async tasks.