I'm trying to use the transaction class from the mssql package of nodejs. So as i read on http://www.dotnetcurry.com/nodejs/1238/connect-sql-server-nodejs-mssql-package, i did the following :
Db.prototype.transaction = function() {
return new Promise((resolve, reject) => {
pool.connect().then(conn => {
let transaction = new mssql.Transaction(conn).begin().then(() => {
new mssql.Request(transaction).query("SELECT * FROM ParkingSlot").then(() => {
transaction.commit().then((recordset) => {
conn.close();
resolve(recordset);
}).catch(reject)
}).catch(reject);
}).catch(reject)
});
});
};
On the caller function, i did db.transaction().then(console.dir); to output any result one console. But nothing happen.
It's because some function of mssql i used on the chains return nothing, so when the promise is pending, he'll work with nothing, as it can be seen on the catch chain in the main call.
Secondly, for using mssql of nodejs with transaction, the connection must be always open (so for my case, in the constructor) and i have to deal with transaction only.
Finally, i don't have to create my request or transaction with a new object. The new instance can be retrieved by ConnectionPool::transaction or ConnectionPool::Request
So here is the final code :
transaction(q) {
return new Promise((resolve, reject) => {
let t = connexion.transaction()
t.begin().then(() => {
let r = t.request();
r.query(q).then((recordset) => {
//console.log(recordset)
t.commit().then((re) => {
conn.close();
}).catch(reject);
resolve(recordset);
})
});
});
}
Note that the code syntax is different, because i pass on ES6 class syntax, better readable.