I know that Javascript's promises are technically neither functors nor monads in the sense of Haskell, because (among other things)
bind
operation that falls back to map
when a pure function is passed in (and thus has an ambiguous type)Promise
constructor and resolve
(aka return
) join nested promises recursivelyThe first issue can easily be bypassed by always providing a function with the right type a -> Promise b
.
The second issue obviously violates the parametricity trait of parametric polymorphic functions, i.e. one cannot construct a m (m a)
structure. But what would this structure mean in the context of promises/asynchronous computations? I cannot think of a meaningful semantics for Promise (Promise a)
, where Promise
is a monad. So what do we lose? What are the implications of the recursive joining?
Provided we are pretty pragmatic (and that's what we should be when we're programming Javascript), can't we claim that a Promise
is a monad in Javascript if we take care of the edge cases?
The first issue can easily be bypassed by always providing a function with the right type
a -> Promise a
.
Or by not using then
as the bind
operation of the monad, but some type-correct ones. Creed is a functionally minded promise library that provides map
and chain
methods which implements the Fantasy-land spec for algebraic types.
The second issue can be bypassed as well with the same approach, by not using resolve
but fulfill
instead, and the static of
method as the unit function.
But what would this structure mean in the context of promises/asynchronous computations?
It's a promise for a promise for a value. Not every constructible type needs to be "meaningful" or "useful" :-)
However, a good example of a similar type is provided by the Fetch API: it returns a promise that resolves to a Response
object, which again "contains" a promise that resolves to the body of the response.
So a Promise (Promise a)
might have only one success result value, which could as well be accessed through a Promise a
, however the two levels of promises
Notice that the Promise
type should have a second type variable for the rejection reason, similar to an Either
. A two-level Promise err1 (Promise err2 a)
is quite different from a Promise err a
.
I know that Javascript's promises are technically neither functors nor monads in the sense of Haskell
You haven't mentioned the biggest issue yet, however: they're mutable. The transition from pending to settled state is a side effect that destroys referential transparency if we consider execution order, and of course our usual use cases for promises involve lots of IO that isn't modelled by the promise type at all.
Promise.delay(50).then(() => Promise.delay(50))
// does something different than
const a = Promise.delay(50); a.then(() => a)
Applying the monad laws is fun and occasionally useful, but we need lots of pragmatism indeed.