JavaScript Promise Failure
A rejection travels down a promise chain. The nearest catch stops it and handles the error.
Catch a rejection
The promise rejects after a short timer. The then step is skipped, and the catch logs the error message.
const p = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("File missing")), 50);
});
p.then((value) => console.log(value))
.catch((err) => console.log("Caught: " + err.message));A throw becomes a rejection
The first step throws an error. The throw turns into a rejection, so the second step is skipped and the catch runs.
Promise.resolve(10)
.then((n) => {
throw new Error("Bad step");
})
.then((n) => console.log(n))
.catch((err) => console.log(err.name + ": " + err.message));Recover after a catch
The catch logs the error and returns a fallback value. The chain fulfills with that value, so the next then runs.
Promise.reject(new Error("No data"))
.catch((err) => {
console.log("Fixed: " + err.message);
return "Fallback data";
})
.then((value) => console.log(value));Example
function stepTwo() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Step two failed")), 50);
});
}
Promise.resolve("Step one done")
.then((message) => console.log(message))
.then(() => stepTwo())
.then((message) => console.log(message))
.catch((err) => console.log("Chain stopped: " + err.message));Key points
- Rejection: a promise that finished with an error
- catch: a method that runs a function when the promise rejects
- A rejection skips every then below it until it reaches a catch.
- A catch returns a new promise, so the chain can keep going.
- A throw inside a then turns into a rejection of the chain.
- A chain without a catch leaves the error unhandled.
In this example, the chain logs the first step, then calls the second step. The second step rejects after a short timer. The rejection skips the next then, and the catch logs the reason the chain stopped.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Where does a rejection stop in a chain?