I'm running into a few different problems when trying to move nested Promise.all's into await/async.
I think I'm just not getting how I should be using Promise.all and await.
I want to do something like below - loop through an array, perform an action on it, and the results being saved to a varibale - ready to be used on the next Promise.all.
doThing()
and doAThing()
are both async functions.
const foo = await Promise.all(arr.map(p => doAThing(p)));
const bar = await Promise.all(foo.map(p => doAnotherThing(p)));
I'm getting lots of undefined, and it's definitely not waiting for the results to fill before continuing.
I'm really just trying to avoid nested promise alls.
Thanks, Ollie
If doAThing()
returns a promise that resolves to a value when all the asynchronous operations in it are done, then foo
will be an array of those resolved values.
If you get undefined
values in the foo
array, then you either aren't returning anything from doAThing()
or you're returning a promise that resolves to undefined
.
If the await
isn't waiting for all the async operations to complete, then you either aren't returning a promise at all from doAThing()
or that promise is getting resolved before all the async operations are done. For all this to work properly, doAThing()
has to return a promise that is ONLY resolved when all the async operations you wanted to wait for are actually done. Promises provide no magic. They have to be wired up properly to resolve when their corresponding asynchronous operations are done. If you have multiple async operations in doAThing()
, then those have to be all monitored together so the function returns a single promise when they are all done (either chained or using Promise.all()
themselves).
For us to help you more specifically, you'd have to show us the code for doAThing()
. Then, we could show you exactly where your code needs fixing.