I am trying to insert multiple rows in PostgreSQL using node pg. I am using transactions but my query is executing after a response. I tried async await with my function but it is not working
This is my function
addPersons = async (req, res) => {
try {
await db.query("BEGIN");
req.body.forEach((person, index) => {
if (person.id) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.IdNotFound.code)
.send(Error_code.IdNotFound);
}
const query = `update person set
name = ${person.name},
where id = '${
person.id
}'`;
try {
await db.query(query);
} catch (error) {
try {
await db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res.status(500).send(err);
}
})
await db.query("COMMIT");
res.status(Error_code.Successfull.code).send(Error_code.Successfull);
} catch (error) {
try {
db.query("ROLLBACK");
} catch (error) {
console.error("Error rolling back client", err.stack);
}
return res
.status(Error_code.UnableToBeginTransaction.code)
.send(Error_code.UnableToBeginTransaction);
}
}
I also tried calling this function from another function and using foreach on that function but when whenever code detects await or callback in the second function it does not wait and return to the first function. How can I run this code to add my data into PostgreSQL with transactions
Thanks