HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

RSVP.hash replacement using ES6 Promise

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rsvphashpromisees6usingreplacement

Problem

We have a pretty big code base that made use of RSVP which we are moving to node 4.3.2+. The only RSVP feature we use frequently that's not in the native js Promise api is the hash() function. I expected to either use the RSVP source or find something on stack overflow. Most people appear to be be solving the problem with different constraints & requirements which makes existing solutions I found somewhat complex so I whipped up my own:

function hash (hashOfPromises) {
  var keys = Object.keys(hashOfPromises);
  return Promise.all(keys.map(function (key) {
    return hashOfPromises[key];
  })).then(function (list) {
    return list.reduce(function (hashOfResolved, value, i) {
      hashOfResolved[keys[i]] = value;
      return hashOfResolved;
    }, {});
  });
}

Solution

I think this is pretty good. I would maybe replace the word "list" with "values".

That said, I think you can simplify this code a bit if you embrace newer versions of js, and perhaps with the use of lodash.

Just a quick example of what you could do:

const _ = require('lodash');

async function hash(hashOfPromises){
    let keys = Object.keys(hashOfPromises);
    let promises = keys.map(key => hashOfPromises[key]);
    let values = await Promise.all(promises);

    return _.zipObject(keys, values);
}

Code Snippets

const _ = require('lodash');

async function hash(hashOfPromises){
    let keys = Object.keys(hashOfPromises);
    let promises = keys.map(key => hashOfPromises[key]);
    let values = await Promise.all(promises);

    return _.zipObject(keys, values);
}

Context

StackExchange Code Review Q#162122, answer score: 2

Revisions (0)

No revisions yet.