I’m looking at a functionality similar to p-props
, p-all
npm library but which recursively resolves promises
const values = {
a: () => Promise.resolve(1),
b: [() => Promise.resolve(2)],
c: {
d: () => Promise.resolve(3),
},
};
console.log(await resolve(values, { concurrency: 2}));
What I’m expecting is {a: 1, b: [2], c: {d: 3}}
and only 2 promises should be running at a time
I see that this can be accomplished by clubbing together p-all, p-props/p-map and their mappers. But not sure about concurrency. Is there any existing approach to such a requirement?
3
Answers
Use the
mapper(value, key)
do thisOutput:
stackblitz
This might work:
You could keep track of the pending promises (in a
Set
) and usePromise.race
to detect when one of those resolves. Then you can execute the next task and add it again to that set, …etc.Use recursion to drill down to those tasks, and as promises resolve (using
Promise.all
), rebuild the object structure with the resolved values.A demo with promises that take varying times to resolve: