0
Basically I want the function below to return a Boolean so I know if the transaction has occurred successfully or not :
public persistirPagamento = async (agencia: string, banco: string, conta: string, saldo: number, valorConta: number, idTransacao: string): Promise<boolean> => {
var resultadoTransacao: boolean = true
var transaction = new mssql.Transaction(this.connection)
await transaction.begin(mssql.ISOLATION_LEVEL.READ_COMMITTED, async (err) => {
if (err != undefined) {
console.error(err)
console.error("Erro no inicio da transação")
resultadoTransacao = err
return
}
var request = new mssql.Request(transaction)
const updateResult = await this.updateAccount(agencia, banco, conta, saldo, request);
if (updateResult != true) {
console.error("Erro no update de valores, rollback")
transaction.rollback()
resultadoTransacao = false// Cancela resto da operação
return
}
const insertMovtoResult = await this.insertMovto(agencia, banco, conta, valorConta, request, idTransacao);
if (insertMovtoResult != true) {
console.error("Erro ao realizar inserção de movto, iniciando rollback...")
transaction.rollback()
resultadoTransacao = false
console.log("Result dentro do inserir movto", resultadoTransacao)
return
}
const resutl = await transaction.commit()
console.log("RESULTADO GERAL DDDD - ", resutl)
})
console.log(resultadoTransacao)
return resultadoTransacao
}
But despite attempts the value of resultadoTransacao
is not changed within the function passed by parameter in transaction.begin
what I notice is that I put comments just before return resultadoTransacao
which is written at the end of the function it is printed before the comments present within the function of the transaction.begin
How can I "sort" the execution of the functions so that my local variable is set correctly ?
The problem is not that the variable is not being changed. It is, but the method
transaction.begin
is asynchronous, so the function switches to direct return before the value has been changed. Try to put aawait
beforetransaction.begin
, so it should wait until the processing has been completed– Paulo Souza
@Paulosouza already tried and it didn’t work :/ the state of the variable always keeps that of initialization.
– viniciusxyz
Observing the documentation of
mssql
realize that the functioncommit
can return a Promise if no callback is passed: https://www.npmjs.com/package/mssql#commit-callback. Thus, it should be possible to use a Try/catch + await block for verification– João Pedro Henrique