2
\$\begingroup\$

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;
    }, {});
  });
}
\$\endgroup\$
1
\$\begingroup\$

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);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.