Skip to content

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

@pwmckenna

Description

@pwmckenna

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());
    };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions