0

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)?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263

2 Answers2

0

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.

mbojko
  • 13,503
  • 1
  • 16
  • 26
0

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));
AKX
  • 152,115
  • 15
  • 115
  • 172