> For the complete documentation index, see [llms.txt](https://strctr.gitbook.io/programming/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://strctr.gitbook.io/programming/01-languages/javascript/01-language/e-controls/e4-promises/04-promise-reactions.md).

# 04. Promise Reactions

> Promise is an object or function with a `then` method whose behavior conforms to this specification.

Клиент, использующий Promise уведомляется о результате выполнения при помощи *реакций callback-ов* (*reactions*), регистрируемых на Promise при помощи методов `then()` и `catch()`:

```javascript
// Setup both reactions
promise.then(onFulfilled, onRejected);

// Setup only onFulfilled reaction
promise.then(onFulfilled);

// Setup only onRejected reaction
promise.then(null, onRejected);

// Setup onRejected reaction
promise.catch(onRejected);

// Setup both reactions
promise.then(onFulfilled).catch(onRejected);
```

![alt text](https://1356653101-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5bu9Zoywb01ca-XJjd%2F-M5buJXbyydR9RxqeVRI%2F-M5buLsf6OLNoCx1FFbN%2Fpromises.png?generation=1587660053031242\&alt=media)

Реакции можно навешивать на Promise в любой момент:

* Реакции, зарегистрированные на Promise до того как он был установлен, сработают после его установки.
* Реакции, зарегистрированные на Promise после того как он был установлен, получают кэшированное значение результата установки.

## Executing reactions

Вызов методов `.then()` и/или `.catch()` всегда возвращает новый Promise в состоянии ожидания. Как только стек исполнения будет свободен, будет вызван *асинхронно* любой из обработчиков (`onFulfilled` or `onRejected`) и Promise перейдет в установленное состояние.

> `onFulfilled` or `onRejected` must not be called until the execution context stack contains only platform code. That means that your code can rely on run-to-completion semantics and that chaining Promises won’t starve other tasks of processing time.

Даже если Promise уже успешно выполнился, то обработчик в любом случае выполняется асинхронно:

```javascript
const promise = Promise.resolve("Success.");
const pending = promise.then(value => console.log(value));

console.log("Is same:", pending === promise); // false
console.log("Done.");
// Is same: false
// Done.
// Success.
```

А promise execution comes with some guarantees:

* Callbacks will never be called before the completion of the current run of the JavaScript event loop.
* Callbacks added with `.then()` even after the success or failure of the asynchronous operation, will be called, as above.
* Multiple callbacks may be added by calling `.then()` several times, to be executed independently in insertion order.

## Promise reactions flow

Note that `.then()` and `.catch()` return a new promise every time. That’s important because chaining can have wildly different results depending on where you append a `.then()` or a `.catch()` call onto.

![alt text](https://1356653101-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M5bu9Zoywb01ca-XJjd%2F-M5buJXbyydR9RxqeVRI%2F-M5buLshtM3MuridXlQg%2Fpromise-reactions.png?generation=1587660053149147\&alt=media)

Поведение Promise похоже на дерево. Добавляйте ветки с помощью `p.then(handler)` и `p.catch(handler)`.
