# Promises — JavaScript

Source: https://www.geekswithgeeks.com/en/javascript/js-promises

> A cleaner way to represent a future value.

## Creating & consuming

`resolve` fulfills the promise, `reject` fails it; `.then()` and `.catch()` react to each outcome.

```js
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Done!"), 1000);
});
promise.then((result) => console.log(result))
       .catch((err) => console.log(err));
```

## Three states

A Promise is **pending**, then settles as **fulfilled** or **rejected** — once settled, it never changes state again.

## Chaining

Each `.then()` returns a new promise, so async steps can be chained in a flat, readable sequence.

```js
fetchUser()
  .then((user) => fetchPosts(user.id))
  .then((posts) => console.log(posts))
  .catch((err) => console.error(err));
```

**Quiz:** What does .catch() handle in a Promise chain?

- [ ] Only network errors
- [x] Any rejection from earlier in the chain
- [ ] Nothing — it's just for logging

*Answer:* Any rejection from earlier in the chain. A rejection at any earlier .then() skips the remaining .then() calls and jumps straight to the nearest .catch().
