JavaScript Promises
A Promise represents a value that may not be available yet — the eventual result of an asynchronous operation. A Promise is always in one of three states: pending, fulfilled, or rejected.
You handle a Promise's outcome with `.then()` for success and `.catch()` for errors, optionally chaining multiple `.then()` calls together.
Creating and consuming
`new Promise((resolve, reject) => {...})` wraps async work. Consumers use `.then(value => ...)` and `.catch(error => ...)` to react to the outcome.
Chaining
Each `.then()` returns a new Promise, allowing you to chain multiple asynchronous steps in sequence, avoiding deeply nested callbacks.
let promise = new Promise((resolve, reject) => {
resolve("Success!");
});
promise.then(result => console.log(result));Success!The Promise resolves immediately, triggering the .then() handler.
function fetchData() {
return new Promise(resolve => resolve(42));
}
fetchData()
.then(data => data * 2)
.then(result => console.log(result));84Each .then() passes its return value to the next, forming a chain.
Key points
- A Promise represents a future value: pending, fulfilled, or rejected.
- .then() handles success, .catch() handles errors.
- Promises can be chained since .then() returns a new Promise.
- Promises avoid deeply nested callback structures.
