I've been experimenting a bit with Typescript, but I'm now a bit stuck on how to use async/await effectively.
I'm inserting a bunch of records into a database, and I need to get the list of IDs that are returned by each insert. The following simplified example works in general, but it is not quite as elegant as I'd like and it is completely sequential.
async function generatePersons() {
const names = generateNames(firstNames, lastNames);
let ids = []
for (let name of names) {
const id = await db("persons").insert({
first_name: name.firstName,
last_name: name.lastName,
}).returning('id');
ids.push(id[0])
}
return ids
}
I tried to use map
to avoid creating the ids
list manually, but I could get this to work.
What I'd also like to have is a limited amount of parallelism. So my asynchronous calls should happen in parallel up to a certain limit, e.g. I'd only ever like to have 10 open requests, but not more.
Is there a reasonably elegant way of achieving this kind of limited parallelism with async/await in Typescript or Javascript ES7? Or am I trying to get this feature to do something it was not intended for?
PS: I know there are bulk insert methods for databases, this example is a bit artificial as I could use those to work around this specific problem. But it made me wonder about the general case where I don't have predefined bulk methods available, e.g. with network requests