'Trying to make a transaction with node-mssql using a for loop
I desperately try to insert into a table several requests using a for loop. The code is supposed to iterate through an array of object and generate SQL requests. The code is based on the node-mssql documentation. If something goes wrong during the process, a rollback is fired, else, at the end of the operation, a commit is fired. I believe I should use the result parameter of the callback but I'm not sure how. If I console.log errors, I get "Can't acquire connection for the request. There is another request in progress."
const connexion_test = async(info)=>
{
var test = [{name:"AB",surname:"BC"},{name:"DE",surname:"EF"},{name:"FG",surname:"GH"},{name:"HI",surname:"HJ"}];
let pool = await sql.connect(sqlConfig)
const transaction = new sql.Transaction(pool)
transaction.begin
(err => {
let rolledBack = false
transaction.on
('rollback', aborted =>
{
// emited with aborted === true
rolledBack = true
})
for (let i=0;i<test.length;i++)
{
new sql.Request(transaction)
.query
(`insert into table_test (nom, prenom) values ('${test[i].name}','${test[i].surname}')`, (err, result) =>
{
if (err)
{
if (!rolledBack)
{
transaction.rollback
(err =>
{
}
)
}
}
else
{
if (i == 0) {
transaction.commit(err => {
})
}
}
}
)
}
})
}
This is a tough one. Thank you for your help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
