Promise/Future: asynchrony in 'then'

Tab Atkins Jr. jackalmage at gmail.com
Thu May 2 14:38:13 PDT 2013


On Thu, May 2, 2013 at 2:28 PM, Claus Reinke <claus.reinke at talk21.com> wrote:
>>    Promise.of(value).then(cb) = cb(value)
>>    promise.then(Promise.of) = promise
>
> My interpretation of these laws for promises is that attaching a callback to
> a resolved promise should execute that callback synchronously (though the
> callback itself may create an asynchronous promise, introducing its own
> delays).

It's not that the callback "may" create an async promise: it *must*
create an async promise, if you want to reason about it in terms of
the monad laws.  The cb must have the signature "a -> Mb", where M in
this case is Promise.  If cb returns a non-promise value, then you're
not following the monad laws, and you can't reason about monadic
behavior.

Assuming it does follow the monad laws properly, then the return value
of cb is *always* accessible in the next tick only, regardless of
whether it runs synchronously or not.  If you're depending on
side-effects, you're already stepping outside of what the monad
abstraction is meant to contain, so slight differences like that are
acceptable.

~TJ


More information about the es-discuss mailing list