promiseForObject.js.flow 716 B

12345678910111213141516171819202122
  1. // @flow strict
  2. import type { ObjMap } from './ObjMap';
  3. /**
  4. * This function transforms a JS object `ObjMap<Promise<T>>` into
  5. * a `Promise<ObjMap<T>>`
  6. *
  7. * This is akin to bluebird's `Promise.props`, but implemented only using
  8. * `Promise.all` so it will work with any implementation of ES6 promises.
  9. */
  10. export default function promiseForObject<T>(
  11. object: ObjMap<Promise<T>>,
  12. ): Promise<ObjMap<T>> {
  13. const keys = Object.keys(object);
  14. const valuesAndPromises = keys.map((name) => object[name]);
  15. return Promise.all(valuesAndPromises).then((values) =>
  16. values.reduce((resolvedObject, value, i) => {
  17. resolvedObject[keys[i]] = value;
  18. return resolvedObject;
  19. }, Object.create(null)),
  20. );
  21. }