How do I modify a local scope variable within a function?

Asked

Viewed 63 times

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 a await before transaction.begin, so it should wait until the processing has been completed

  • @Paulosouza already tried and it didn’t work :/ the state of the variable always keeps that of initialization.

  • Observing the documentation of mssql realize that the function commit 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

1 answer

2


It would not be enough to return the boolean by its method?

You can use common Promise syntax (no async/await) to work with returns within callbacks

public persistirPagamento = (agencia: string, banco: string, conta: string, saldo: number, valorConta: number, idTransacao: string): Promise<boolean> => new Promise((resolve, reject) => {

    var transaction = new mssql.Transaction(this.connection)

    transaction.begin(mssql.ISOLATION_LEVEL.READ_COMMITTED, async (err) => {

        if (err != undefined) {
            console.error(err)
            console.error("Erro no inicio da transação")
            resolve(false);
            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()
            resolve(false)
            return // Cancela resto da operação
        }


        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()
            resolve(false)
            return 
        }

        transaction.commit((err: boolean) => {
            resolve(!err) //Retorna negação do erro ou seja se houve erro retorno false, se não houve retorna true
        });
    });
});

//dentro de uma função assincrona
var sucesso = await Banco.persistirPagamento(...);
if (sucesso) console.log('Operação realizada');
else console.log('Erro durante a transação');
  • It worked perfectly, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.