Promises
A Promise represents a value that may not be available yet — it can be pending, fulfilled, or rejected. Promises are the foundation that async/await is built on.
Promises let you chain asynchronous operations with `.then()` and handle failures with `.catch()`, avoiding deeply nested callbacks.
Creating a promise
The `Promise` constructor takes a function with `resolve` and `reject` parameters, called when the async operation finishes.
Chaining promises
`.then()` returns a new Promise, letting you chain multiple asynchronous steps; `.catch()` handles any rejection in the chain.
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
wait(1000).then(() => console.log('1 second passed'));1 second passedThe Promise resolves after the timeout, then .then() runs.
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => console.log(posts))
.catch(err => console.error(err));[...] or an error is logged.then() chains dependent async steps; .catch() handles any failure along the chain.
Key points
- A Promise can be pending, fulfilled, or rejected.
- resolve()/reject() settle a Promise's outcome.
- .then() chains follow-up actions; .catch() handles errors.
- async/await is built on top of Promises.
