A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Think of it like a "promise" someone makes:
“I promise I’ll give you the data... just wait a moment!”
🔁 Why Promises?
JavaScript is asynchronous — it doesn’t wait for things like API calls or file reads. Before Promises, we used callbacks, which could lead to callback hell 😵
Promises make async code cleaner, more readable, and easier to manage.
🔧 Syntax
const promise = new Promise((resolve, reject) => {
// async task
if (/* everything is good */) {
resolve('Success!');
} else {
reject('Error!');
}
});
-
resolve(value)
→ when async task is successful -
reject(error)
→ when async task fails
✅ Consuming a Promise
promise
.then((result) => {
console.log('Resolved:', result);
})
.catch((error) => {
console.log('Rejected:', error);
})
.finally(() => {
console.log('Always runs');
});
🕰 Real Example (setTimeout)
const wait = new Promise((resolve) => {
setTimeout(() => {
resolve('Done waiting!');
}, 2000);
});
wait.then(console.log); // After 2 sec → "Done waiting!"
📦 Built-in Promises Example (Fetch)
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
🧠 Promise States
- Pending – Initial state
- Fulfilled – Resolved with a value
- Rejected – Failed with an error
⛓ Chaining Promises
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.catch(error => console.error(error));
✨ Bonus: Async/Await (Built on Promises)
async function fetchData() {
try {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}