JavaScript Intermediate
What is a Promise in JavaScript? What is it used for?
What is a Promise?
A Promise is an object representing an asynchronous operation that is not yet complete, but will eventually succeed or fail. It solves the "Callback Hell" problem.
Three States
| State | Description |
|---|---|
| Pending | Initial state, operation not yet complete |
| Fulfilled | Operation succeeded, has a return value |
| Rejected | Operation failed, has an error reason |
Once a state changes, it is irreversible.
Basic Usage
// Creating a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve('Operation succeeded!');
} else {
reject(new Error('Operation failed!'));
}
}, 1000);
});
// Consuming a Promise
promise
.then(result => console.log(result)) // 'Operation succeeded!'
.catch(error => console.error(error))
.finally(() => console.log('Done'));
Promise Chaining
fetch('/api/user')
.then(res => res.json())
.then(user => fetch('/api/posts?userId=' + user.id))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
async/await (Syntactic Sugar)
async function loadData() {
try {
const res = await fetch('/api/user');
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
}
Common Static Methods
| Method | Description |
|---|---|
Promise.all() |
Resolves when ALL fulfill; rejects if any rejects |
Promise.race() |
Settles with the first to complete (success or failure) |
Promise.allSettled() |
Waits for ALL to settle, regardless of outcome |
Promise.any() |
Resolves when ANY fulfills |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
