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);
}
}
Top comments (0)