Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a `map` operation on the promised values of an object?

Tags:

javascript

I'm familiar with doing an map operation like this on arrays

[1,2,3].map(x=>x = x + 1);

What I have is a map of promises e.g.

const objOfPromises = {
  'a': Promise.resolve(1),
  'b': Promise.resolve(2),
  'c': Promise.resolve(3),
}

Is there a way of doing something like

const objOfResolvedPromises = await objOfPromises.map(promise => await promise)
like image 858
Archimedes Trajano Avatar asked Oct 28 '25 05:10

Archimedes Trajano


1 Answers

Map to an array of Promises that resolves to an entry array (an array with 2 elements, a key and a value), and use Promise.all and then Object.fromEntries to turn it back into an object.

const objOfPromises = {
  'a': Promise.resolve(1),
  'b': Promise.resolve(2),
  'c': Promise.resolve(3),
};
Promise.all(
  Object.entries(objOfPromises).map(
    ([key, prom]) => prom.then(resolveVal => [key, resolveVal])
  )
)
  .then((resolvedEntries) => {
    const objOfResolvedPromises = Object.fromEntries(resolvedEntries);
    console.log(objOfResolvedPromises);
  });
like image 150
CertainPerformance Avatar answered Oct 29 '25 20:10

CertainPerformance