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
- might fulfill at different times, adding a "middle step"
- might reject with different causes - e.g. the outer one representing a network problem while the inner one represents a parsing problem
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…