Hacker News new | ask | show | jobs
by spion 3943 days ago
Yes. Infact, a JavaScript Promise is pretty much the same as the IO monad* - the `then` method is a lot like `bind`. Promise.resolve is a lot like `return`

* almost the same to IO, because of recursive thenable assimilation, something that was added to promises but is totally short-sighted and unnecessary; and because promises are eager which means they don't represent the action to be executed, but the value of an already executed action

2 comments

I find it interesting that people complain about Haskell's monadic IO, and yet nodejs event-driven IO is arguably the same idea but without the syntactic sugar.
A concise and good explanation thanks.
Note that the word "monad" itself refers just to the "shape" of the object (and some rules about that shape), not the functionality.

For example, an array can be a monad if we define a bind method as map + flatten

  Array.prototype.flatMap = function(f) {
    return _.flatten(this.map(f))
  }
which works like so:

  allArticles = authors.flatMap(author => author.articles);
return would be

  Array.of = function(val) { return [val]; }
The shape (type) is the same:

the promise's bind (then) method takes a function that takes a value and returns a promise, and returns another promise

the array's bind (flatMap) method takes a function that takes a value and returns an array, and returns another array

the promise's return (Promise.resolve) method takes a value and wraps it in a promise

the array's return (Array.of) method takes a value and wraps it in an array.

You can get the array method types (shapes) from the promise ones by replacing promise with array (if you decide to give the methods the same name).

The implemented functionality, however, is vastly different.