I have the given code snippet:
async function seedDb() {
let users: Array<Users> = [ ... ];
applications.map(async (user) => await prisma.user.upsert(
{ create: user, update: {}, where: { id: user.id } }));
}
async function main() {
await seedDb();
await seedDb2(); // This requires the update in seedDb() to have completed
}
The problem here is that other functions like seedDb2
rely on the presence of users in the database before running. While all updates start in seedDb
, there is no actual waiting (blocking) until those functions finish.
What I want is to wait until all the async functions spawned by the map method return. How can this be achieved?
I am unsure about how await
behaves. I understand that it pauses execution and waits for the promise to be fulfilled within that context, but how can it truly block execution? Is there something equivalent to threads.join()
?
In C++, I would typically create threads to update the database and then join them all at the end before returning from seedDb. What is the correct approach to achieve this in TypeScript?
Using
return await Promise.all(applications.map(async (user) => await prima.user.upsert(...))
(as suggested in a linked StackOverflow question) seems incorrect to me - different functions (seedDb2
) could still be running before the promises created by seedDb
are finished, which contradicts my goal.
[0] A side inquiry - why use await Promise.all()
? Doesn't Promise.all
already resolve the promise and return the appropriate type, so why follow it with await again?