04. Promise Reactions
Last updated
Was this helpful?
Last updated
Was this helpful?
Promise is an object or function with a
then
method whose behavior conforms to this specification.
Клиент, использующий Promise уведомляется о результате выполнения при помощи реакций callback-ов (reactions), регистрируемых на Promise при помощи методов then()
и catch()
:
Реакции можно навешивать на Promise в любой момент:
Реакции, зарегистрированные на Promise до того как он был установлен, сработают после его установки.
Реакции, зарегистрированные на Promise после того как он был установлен, получают кэшированное значение результата установки.
Вызов методов .then()
и/или .catch()
всегда возвращает новый Promise в состоянии ожидания. Как только стек исполнения будет свободен, будет вызван асинхронно любой из обработчиков (onFulfilled
or onRejected
) и Promise перейдет в установленное состояние.
onFulfilled
oronRejected
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 уже успешно выполнился, то обработчик в любом случае выполняется асинхронно:
А 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.
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)
.