RSVP hash using vanilla promises

165 views Asked by At

RSVP lib has a hash of promises helper that allows to "retrieve" promises references:

var promises = {
  posts: getJSON("/posts.json"),
  users: getJSON("/users.json")
};

RSVP.hash(promises).then(function(results) {
  console.log(results.users) // print the users.json results
  console.log(results.posts) // print the posts.json results
});

Is there a way to do such a thing with vanilla promises (in modern ES)?

2

There are 2 answers

1
AKX On BEST ANSWER

It's not hard to implement.

async function hash(promiseObj) {
  // Deconstitute promiseObj to keys and promises
  const keys = [];
  const promises = [];
  Object.keys(promiseObj).forEach(k => {
    keys.push(k);
    promises.push(promiseObj[k]);
  });
  // Wait for all promises
  const resolutions = await Promise.all(promises);
  // Reconstitute a resolutions object
  const result = {};
  keys.forEach((key, index) => (result[key] = resolutions[index]));
  return result;
}

hash({
  foo: Promise.resolve(8),
  bar: Promise.resolve(16),
}).then(results => console.log(results));
0
mbojko On

OOTB? No, there's only Promise.all, but it accepts an array, not a dictionary. But you could create a helper function that accepts a dictionary of promises, converts to array, runs Promise.all on it, and processes it with one more then converting the results array back into a dictionary.