What is a promise?
- JavaScript course
- Intermediate
- Lesson 72/134
- 5 min
Learn the promise states: pending, fulfilled and rejected.
What is a promise?
A promise is an object that represents the eventual result of an asynchronous operation. It is in one of three states: pending, fulfilled or rejected.
Once a promise settles, it becomes immutable: a fulfilled promise cannot go back to pending. This stability removes the confusion of callback hell and makes chaining easy. Promises are the modern replacement for callbacks.
Creating a promise
A promise is created with new Promise. The constructor takes a function that receives two parameters: resolve and reject. If the work succeeds, you call resolve with the value; if it fails, you call reject with the error.
const order = new Promise((resolve, reject) => {
if (inStock) {
resolve('shipped');
} else {
reject('out of stock');
}
});resolve and reject are called only once; later calls are ignored.
Practice Write a stock-check promise
Write a function called checkStock. It takes a quantity parameter and returns a Promise. If quantity is greater than 0, call resolve with true; otherwise call reject with the string 'out of stock'.
Starter code
function checkStock(quantity) {
return new Promise((resolve, reject) => {
// write the stock check
});
}Sample solution
function checkStock(quantity) {
return new Promise((resolve, reject) => {
if (quantity > 0) {
resolve(true);
} else {
reject('out of stock');
}
});
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens after a promise becomes fulfilled?
- It can return to pending
- It automatically becomes rejected
- Its state stays fixed and its value does not change Correct answer
- It must create a new promise
Explanation: Once a promise settles, its state and value stay fixed.
2 Fulfil the promise
const loaded = new Promise((resolve, reject) => {
____;
});
const loaded = new Promise((resolve, reject) => {
resolve(data);
});
Explanation: resolve(data) fulfils the promise.
3 Match states to their meanings
| Term | Meaning |
|---|---|
pending |
Result still awaited |
fulfilled |
Success, value ready |
rejected |
Failure, error present |