pwmckenna / til

Today I Learned
http://pwmckenna.net
9 stars 8 forks source link

Turning Q promises into a lodash fueled "monad" #27

Open pwmckenna opened 7 years ago

pwmckenna commented 7 years ago

Inspired by working with for comprehensions in scala, I wanted to just write long chains of transformations in javascript without breaks to convert between promises and the underlying types. Q already has a touch of this with the ability to call .get(key) on a promise to pull a key off of the resolved object.

What I wanted to write:

const fetchRepos = Q(fetch('https://api.github.com/orgs/octokit/repos'))
const repoNames = await fetchRepos()
    .filter(({ language }) => language === 'JavaScript')
    .map('name');

The implementation was pretty simple, as long as you're willing to globally modify Q's Promise.

import Q from 'q';
import _ from 'lodash';
for (let f in _.prototype) {
    Q.makePromise.prototype[f] = function (...args) {
        return this.then(value => _(value)[f](...args).value());
    };
}