Skip to content

Instantly share code, notes, and snippets.

@rolangom
Last active July 30, 2018 22:04
Show Gist options
  • Save rolangom/8dd4e044bd450abda0adabf12646d6e4 to your computer and use it in GitHub Desktop.
Save rolangom/8dd4e044bd450abda0adabf12646d6e4 to your computer and use it in GitHub Desktop.
JS Promise and Applicative Functor
Promise.prototype.ap = function(p) {
const self = this;
return p.then(v => self.then(f => f(v)));
}
const add =
a => b => a + b;
console.log(add(1)(2)); // 3
Promise.resolve(add)
.ap(Promise.resolve(1))
.ap(Promise.resolve(2))
.then(console.log); // 3
Promise.resolve(1)
.then(add)
.ap(Promise.resolve(2))
.then(console.log); // 3
Promise.resolve(add(1))
.ap(Promise.resolve(2))
.then(console.log) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment