A Promise in JavaScript represents the eventual completion or failure of an asynchronous operation. Promises help us organize asynchronous code without deeply nesting callbacks.
A Promise is an object used to handle the result of an asynchronous operation. It can be fulfilled with a value or rejected with a reason, such as an error.
| State | Meaning |
|---|---|
Pending |
The operation has not settled yet. |
Fulfilled |
The operation completed successfully. |
Rejected |
The operation failed. |
We create a Promise using the new Promise()
constructor. Its executor function receives two functions:
resolve() and reject().
const myPromise = new Promise((resolve, reject) => {
resolve('Operation successful!');
});
myPromise.then((result) => {
console.log(result);
});
Operation successful!
The resolve() function fulfills the Promise.
The .then() method handles its successful result.
Use resolve() to fulfill a Promise and
reject() to reject it.
const promise = new Promise((resolve, reject) => {
const marks = 80;
if (marks >= 40) {
resolve('Student passed!');
} else {
reject(new Error('Student failed.'));
}
});
promise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error.message);
});
Student passed!
Since the marks are 80, the Promise is fulfilled. If the marks were below 40, it would be rejected.
The .then() method registers handlers for a
fulfilled Promise. It can also accept a rejection handler as
its second argument, although .catch() is often
clearer for error handling.
const promise = Promise.resolve(100);
promise.then((value) => {
console.log('Value:', value);
});
Value: 100
Promise.resolve(100) creates a fulfilled
Promise containing the value 100.
The .catch() method handles a rejected Promise.
It is commonly used to handle errors from a Promise chain.
const promise = new Promise((resolve, reject) => {
reject(new Error('Something went wrong!'));
});
promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log('Error:', error.message);
});
Error: Something went wrong!
Because the Promise is rejected, the
.catch() handler processes the error.
The .finally() method runs when a Promise settles,
whether it fulfills or rejects. It is useful for cleanup tasks.
Promise.resolve('Data loaded')
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message);
})
.finally(() => {
console.log('Operation finished.');
});
Data loaded
Operation finished.
The finally() callback runs after the
Promise settles, regardless of whether it succeeds
or fails.
Promise chaining allows us to perform multiple operations in
sequence. Each .then() can return a value or another
Promise for the next step.
Promise.resolve(10)
.then((number) => {
console.log('Original:', number);
return number + 5;
})
.then((number) => {
console.log('After addition:', number);
return number * 2;
})
.then((number) => {
console.log('Final result:', number);
})
.catch((error) => {
console.log('Error:', error.message);
});
Original: 10
After addition: 15
Final result: 30
Each handler returns a value that becomes the input for the next fulfilled handler.
We can create a Promise that fulfills after a delay. This technique is useful for learning asynchronous execution.
function getMessage() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Message received!');
}, 2000);
});
}
console.log('Start');
getMessage().then((message) => {
console.log(message);
});
console.log('End');
Start
End
Message received!
The Promise fulfills after approximately two seconds.
The synchronous console.log() statements
execute first.
These static methods create fulfilled or rejected Promises. They are useful when a Promise is needed without writing the constructor directly.
Promise.resolve('Success')
.then((message) => {
console.log(message);
});
Promise.reject(new Error('Failure'))
.catch((error) => {
console.log(error.message);
});
Success
Failure
Promise handlers run asynchronously as microtasks. The two independent examples above schedule their handlers in the order shown.
Promise.all() accepts an iterable of Promises and
fulfills when all of them fulfill. If any input Promise rejects,
the returned Promise rejects with that reason.
const p1 = Promise.resolve('Student data');
const p2 = Promise.resolve('Course data');
const p3 = Promise.resolve('Fee data');
Promise.all([p1, p2, p3])
.then((results) => {
console.log(results);
})
.catch((error) => {
console.log('Error:', error.message);
});
[
'Student data',
'Course data',
'Fee data'
]
The results are returned in the same order as the input Promises, not necessarily in the order they finish.
Promise.allSettled() waits for every input Promise
to settle. Its result describes whether each Promise fulfilled
or rejected.
const p1 = Promise.resolve('Success');
const p2 = Promise.reject(new Error('Failed'));
Promise.allSettled([p1, p2]).then((results) => {
results.forEach((result) => {
console.log(result.status);
});
});
fulfilled
rejected
Unlike Promise.all(),
Promise.allSettled() reports the outcome
of every input Promise.
| Method | Purpose |
|---|---|
.then() |
Handles fulfillment and returns a new Promise. |
.catch() |
Handles rejection and returns a new Promise. |
.finally() |
Runs cleanup logic after settlement. |
Promise.resolve() |
Creates a fulfilled Promise or adopts a Promise-like result. |
Promise.reject() |
Creates a rejected Promise. |
Promise.all() |
Fulfills when all inputs fulfill; rejects if an input rejects. |
Promise.allSettled() |
Waits for every input Promise to settle. |
Promise.race() |
Settles with the first input Promise to settle. |
Promise.any() |
Fulfills with the first fulfilled input, or rejects if all reject. |
This example checks a student's marks using a Promise and displays the result.
function checkResult(marks) {
return new Promise((resolve, reject) => {
if (marks >= 40) {
resolve('Congratulations! You passed.');
} else {
reject(new Error('Sorry! You failed.'));
}
});
}
checkResult(75)
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error.message);
})
.finally(() => {
console.log('Result checking completed.');
});
Congratulations! You passed.
Result checking completed.
Try changing 75 to 25 and run
the program again to see the rejected result.
.catch()..finally() to display a completion message..then().Promise.all() to collect three results.Promise.allSettled() to inspect successful and failed Promises.Challenge: Create three Promise-based functions to get a student, course, and fee. Chain them together and handle errors in one place.
Select the correct answer for each question.
1. How many main states does a Promise have?
2. Which method is commonly used to handle a rejected Promise?
3. Which method waits for every input Promise to settle?