What is a promise?
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.
Exercise 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'.
Show example solution
function checkStock(quantity) {
return new Promise((resolve, reject) => {
if (quantity > 0) {
resolve(true);
} else {
reject('out of stock');
}
});
}
Test yourself
-
What happens after a promise becomes fulfilled?
- It can return to pending
- Its state stays fixed and its value does not change
- It automatically becomes rejected
- It must create a new promise
Show answer
Its state stays fixed and its value does not change — Correct! Once a promise settles, its state and value stay fixed.
-
Fulfil the promise
const loaded = new Promise((resolve, reject) => { ____; });Show answer
const loaded = new Promise((resolve, reject) => { resolve(data); }); -
Match states to their meanings
- pending
- Result still awaited
- fulfilled
- Success, value ready
- rejected
- Failure, error present