Promise
What is a Promise?
"Represents eventual completion of async operation"
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
"A Promise is an object that represents the eventual result of an asynchronous operation, with states of pending, fulfilled, or rejected."
Promise States
Pending → Fulfilled or Rejected
| State | Meaning |
|---|---|
| Pending | Initial state, not fulfilled or rejected |
| Fulfilled | Operation completed successfully |
| Rejected | Operation failed |
"Promises have three states: pending, fulfilled (resolved), or rejected."
Creating Promises
new Promise(resolve, reject)
const promise = new Promise((resolve, reject) => {
if (success) {
resolve(value);
} else {
reject(error);
}
});
"Promises are created with a constructor that takes resolve and reject callbacks."
Promise Methods
then · catch · finally
promise
.then((value) => {
// handle success
})
.catch((error) => {
// handle error
})
.finally(() => {
// always runs
});
"then handles fulfillment, catch handles rejection, and finally runs regardless of outcome."
Promise Chaining
Return promises to chain
fetch("/api/data")
.then((response) => response.json())
.then((data) => processData(data))
.then((result) => console.log(result))
.catch((error) => console.error(error));
"Promises can be chained by returning values or new promises from then handlers."
Promise.all()
Wait for all, fail fast
Promise.all([promise1, promise2, promise3])
.then((values) => {
// all resolved
})
.catch((error) => {
// any rejected
});
- Resolves when all fulfill
- Rejects if any reject
"Promise.all waits for all promises to resolve, or rejects if any promise rejects."
Promise.allSettled()
Wait for all, never fails
Promise.allSettled([promise1, promise2]).then((results) => {
// all completed (success or failure)
});
- Waits for all to complete
- Never rejects
"Promise.allSettled waits for all promises to settle, regardless of success or failure."
Promise.race()
First to settle wins
Promise.race([promise1, promise2]).then((value) => {
// first to resolve/reject
});
"Promise.race resolves or rejects with the first promise to settle."
Async/Await
Synchronous-looking async code
async function fetchData() {
try {
const response = await fetch("/api/data");
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
"Async/await provides a cleaner syntax for working with promises, making async code look synchronous."
Error Handling
try/catch with async/await
async function example() {
try {
const result = await promise;
} catch (error) {
// handle error
}
}
Or with .catch():
promise
.then(...)
.catch(error => {
// handle error
});
🧠 Ultra-Short Cheat Sheet
Pending → Fulfilled/Rejected
then/catch/finally
Chaining
Promise.all (all or fail)
Promise.race (first wins)
Promise.allSettled (all complete)
async/await
Error handling