Search code examples
javascriptasynchronouspromise

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}


Solution

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