Is Promise a Monad?

March 17, 2020

TL;DR

I think so.

Monad laws

From https://wiki.haskell.org/Monad_laws:

Ported to JavaScript

var resolve =
  function (x) {
    return Promise.resolve(x);
  };

var a = 1

var m = resolve(a);

var f =
  function (x) {
    return resolve(x * 6);
  };

var g =
  function (x) {
    return resolve(x * 7);
  };

Verification

var equals =
  function(p1, p2) {
    Promise.all([p1, p2])
           .then(
             function (xs) {
               if (xs[0] !== xs[1]) {
                 throw Error(xs[0] + " !== " + xs[1]);
               }
             }
           );
  };

// Left identity
equals(resolve(a).then(f), f(a));

// Right identity
equals(m.then(resolve), m);

// Associativity
equals( (m.then(f)).then(g)
      , m.then(function (x) {
                 return f(x).then(g);
               }
              )
      );

console.log('done')

Demo

This file is literate JavaScript, and can be run using Codedown:

$ curl https://earldouglas.com/javascript/promisem.md |
  codedown javascript |
  node
done