How to ´Promise.all´ the values of a JS hash

For doing something like this:

var hash = { key1: value1, key2: promise2, ... };
Promise.all(hash).then(hash => ...);

I wrote this little function:

  function promiseAll(hash) {
    const keys = Object.keys(hash);
    const values = keys.map(key => hash[key]);
    return Promise.all(values).then(resolved_values => {
      const resolved_hash = {};
      keys.forEach((key, index) => {
        resolved_hash[key] = resolved_values[index];
      });
      return resolved_hash;
    });
  }

which allows you to do this:

var hash = { key1: value1, key2: promise2, ... };
promiseAll(hash).then(hash => ...);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.