I have a req.body from a Post form with many values like this
console.log(req.body)
{
productid:[1, 2, 3]
qty: [3, 5, 6]
}
I want to make a for loop and use the different values in a SQL query But I get stuck on the first query problaby because its an async await function.
My question is how can I do many sql queries with a forloop and still use an async await function?
CodePudding user response:
You can do it like this:
for(let item of array) {
let res = await query(item)
}
CodePudding user response:
Since I only do an update and not waiting for an answer I didnt need to use await async. It worked when I remove async/await.
Thank you
Sorry for not so clear question
CodePudding user response:
if you want to do them in parallel you can create an array of promises and use Promise.all to wait for all the operations to finish, in this way you can optimize you code a lot instead of doing in a sequential way.
const operations = []
for(let item of array) {
operations.push(query(item))
}
const result = await Promise.all(operations)
//Do wherever you want with your results.
In order to execute your code, your function which handle the request must be declared with the async keyword.