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():

// 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);

Реакции можно навешивать на 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 уже успешно выполнился, то обработчик в любом случае выполняется асинхронно:

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.

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

Last updated