What is a Promise?
Definition
Promise is a special object in JavaScript
that represents the result of an asynchronous operation,
which may complete later - successfully or with an error.
In simpler terms, a Promise is a "promise" to deliver a result in the future. There is no answer right now, but there will be one once the operation finishes.
Three states of a promise
| State | Description | Example |
|---|---|---|
| pending | "waiting" - the operation has not finished yet | a request in progress |
| fulfilled | "completed successfully" - there is a result | data received |
| rejected | "rejected" - an error occurred | the server returned 404 |
Example 1 - Creating a promise manually
const promise = new Promise((resolve, reject) => {
const success = Math.random() > 0.5;
if (success) {
resolve('Success!');
} else {
reject('Error!');
}
});resolve(value)moves the promise to the fulfilled state;reject(error)moves it to the rejected state.
Handling the result
promise
.then((result) => {
console.log('Result:', result);
})
.catch((error) => {
console.error('Error:', error);
})
.finally(() => {
console.log('Always runs');
});What each method does:
| Method | When it is called | What it returns |
|---|---|---|
.then() | on success (resolve) | a new Promise |
.catch() | on an error (reject) | a new Promise |
.finally() | in either case (success or error) | a new Promise |
Example 2 - Asynchronous code with Promise
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data received!');
}, 2000);
});
}
fetchData().then((data) => console.log(data));fetchData() returns a Promise ->
after 2 seconds it resolves, and then() receives the result.
Example 3 - Handling errors
function fetchUser() {
return new Promise((_, reject) => {
setTimeout(() => reject('User not found'), 1000);
});
}
fetchUser()
.then(user => console.log(user))
.catch(err => console.error(err));Output:
User not foundPromise chaining
Every .then() returns a new Promise,
so you can build chains of asynchronous actions:
getUser()
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log(comments))
.catch(err => console.error('Error:', err));Advantage: No nesting -> reads top to bottom (unlike callback hell).
Shorthand form - Promise.resolve() and Promise.reject()
Promise.resolve('OK').then(console.log); // "OK"
Promise.reject('Error').catch(console.error); // "Error"Parallel promises
Promise.all() - waits until all of them complete
Promise.all([
fetch('/user'),
fetch('/posts'),
]).then(([userRes, postRes]) => {
console.log('Both responses received');
});If even one promise ends with an error, the whole all() becomes rejected.
Promise.allSettled() - waits for all of them, regardless of errors
Promise.allSettled([
fetch('/user'),
fetch('/wrong-url'),
]).then(console.log);Result:
[
{ status: "fulfilled", value: Response },
{ status: "rejected", reason: TypeError }
]Promise.race() - returns the first one to complete
Promise.race([
fetch('/slow'),
fetch('/fast'),
]).then(console.log);Promises and async/await
Promises are the foundation that async/await syntax is built on:
async function main() {
try {
const user = await getUser();
const posts = await getPosts(user.id);
console.log(posts);
} catch (err) {
console.error(err);
}
}Here await simply waits for a Promise, but makes the code linear and clear.
A simple analogy
A promise is like a pizza delivery.
- You place an order -> the promise is created (pending)
- The courier is bringing the order -> the operation is in progress
- The courier arrives -> the promise resolves
- The courier gets lost -> the promise rejects
You can "subscribe" to the result (
then) and "handle" errors (catch).
SUMMARY
| Term | Description |
|---|---|
| Promise | An object representing the future result of an asynchronous operation |
| States | pending -> fulfilled or rejected |
| Methods | .then(), .catch(), .finally() |
| Main advantage | Simplifies working with asynchrony, removes callback hell |
| Modern syntax | async/await is built on Promise |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.