I have the following code:
async function seedDb() {
let users: Array<Users> = [ ... ];
applications.map(async (user) => await prisma.user.upsert(
{ create: user, update: {}, where: { id: user.id } }));
}
The issue is that there other seedDb functions (e.g. seedDb2
) which rely on the users being present. But while I start all the updates in seedDb
, I do not actually wait (in the sense of blocking) until those functions finished.
What I would like to do is to block until all the async functions spawned by the map return. How do I achieve this?
I don’t fully understand how await
works. I get that it allows to interrupt execution and waits in that context until the promised is fulfilled, but how do you make it actually block execution? Something like threads.join()
?
In C++ for example I would create threads that update the database and then join all of them at the end before returning from seedDb. What is the recommended way of doing this in typescript?
Using return await Promise.all(applications.map(async (user) => await prima.user.upsert(...))
(suggested by a linked so question) seems to me to be incorrect too – different functions (seedDb2
) might still be running before those promises are finished.
[0] Side question – what is the point of using await Promise.all()
? Doesn’t Promise.all
already resolve the promise and return the actual type, why are we calling await again?
The code does not work, I do not understand how await works. I get that it resolves a promise, but how do you tell it ‘ok but also block now’?
Heremit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.