Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.all for objects in Javascript

Promise.all can turn [Promise a, Promise b] into Promise [a, b], which is super useful, but is there also a way to turn {a: Promise a, b: Promise b} into Promise {a, b}.

The use case is:

I have a function that loads some files from a website and gives back error messages in the case that it failed. This means, that its signature is information -> {values: values, messages: messages}.

But the whole check is async, so it turns out to be information -> {values: Promise values, messages: promise messages}

like image 533
hgiesel Avatar asked Jun 17 '26 14:06

hgiesel


1 Answers

Here's my super simple solution:

export const objectZip = (keys, values) =>
  keys.reduce(
    (others, key, index) => ({
      ...others,
      [key]: values[index],
    }),
    {}
  );

export const objectPromise = async obj =>
  objectZip(Object.keys(obj), await Promise.all(Object.values(obj)));
like image 97
Remco Avatar answered Jun 19 '26 05:06

Remco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!