javascriptpromiseasync-awaitrsvp.js

RSVP hash using vanilla promises


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


Solution

  • 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));