# Is `Promise` a monad?

March 17, 2020

## TL;DR

I think so.

• Left identity: `return a >>= f ≡ f a`
• Right identity: `m >>= return ≡ m`
• Associativity: `(m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)`

### Ported to JavaScript

• Let `return` be `resolve`
• Let `a` be `1`
• Let `m` be a `Promise` of `a`
• Let `>>=` be `then`
``````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/snippets/promise.md |
codedown javascript |
node
done``````