Q16 of 40 · JavaScript
What is a Promise, and how do you handle fulfillment, rejection, and cleanup?
Short answer
Short answer: A Promise represents an eventual value in one of three immutable states: pending, fulfilled, or rejected. Use `.then()` for fulfilled values, `.catch()` for rejections, and `.finally()` for cleanup regardless of outcome. Once settled, a Promise cannot change state.
Detail
A Promise is an object representing the eventual completion or failure of an async operation. It was introduced to avoid callback hell and enable composable async logic.
States: A Promise starts as pending. It transitions to fulfilled (with a value) or rejected (with a reason). Transitions are final — a fulfilled Promise cannot become rejected.
Chaining: .then() returns a new Promise, allowing chains. Returning a value from .then() wraps it in a fulfilled Promise. Throwing inside .then() creates a rejection that propagates to the next .catch().
Error propagation: An unhandled rejection propagates down the chain until a .catch() handles it. Unhandled rejections in Node.js emit a warning and in newer versions can crash the process.
Creating Promises: new Promise((resolve, reject) => {}) for wrapping legacy async code. For known values: Promise.resolve(value) or Promise.reject(reason).
In test automation: Most async test framework APIs return Promises. Returning or awaiting them is mandatory — forgetting to await causes tests to complete before assertions run.
// EXAMPLE
// Creating a Promise wrapping a callback API
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Chaining with error handling
fetch("/api/user/1")
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(user => console.log(user.name))
.catch(err => console.error("Failed:", err.message))
.finally(() => console.log("done — success or failure"));
// Known value shortcuts
Promise.resolve(42).then(v => console.log(v)); // 42
Promise.reject(new Error("oops")).catch(e => console.error(e.message));