Returning callback values in the main function - JS / NodeJS

0

I have a main function and a callback function inside it. I need that, depending on the callback return my main function returns something, note:

function funcaoPrincipal(){
    funcaoCallback(function(erro){
        if(erro){
            //retorna false para a função principal
        }else{
            //retorna true para a função principal
        }
    });
}

How can I accomplish this? I have already tried declaring a variable within the scope of the main function and modifying it within the callback, but without success.

    
asked by anonymous 06.09.2017 / 17:01

1 answer

1

One way to do this is to use a variable in funcaoPrincipal and change its value within callback :

function funcaoPrincipal(){
    let deuErro;
    funcaoCallback(function(erro) {
        if(erro) {
            deuErro = true;
        } else {
            deuErro = false;
        }
    });
    console.log(deuErro) // true;
}

However, if the callback is executed asynchronously, it will not be available immediately below your call:

function funcaoPrincipal(){
    let deuErro;
    funcaoCallback(function(erro) {
        if(erro) {
            deuErro = true;
        } else {
            deuErro = false;
        }
    });
    // quando chegar aqui, não vai ter passado pelo callback
    console.log(deuErro); // undefined
}

One solution would be to do what you are doing in funcaoPrincipal in the callback:

function funcaoPrincipal(){
    let deuErro;
    funcaoCallback(function(erro) {
        if(erro) {
            deuErro = true;
        } else {
            deuErro = false;
        }

        // trabalhar com a variável aqui
        console.log(deuErro); // true
    });
}

But an even more interesting way would be to use a Promise .

With this, I could do something like:

function funcaoPrincipal() {

    funcaoCallback()
        .then(function() {
            // sucesso
        })
        .catch(function () {
            // erro
        });
}

function funcaoCallback() {
    return Promise(function (resolve, reject) {
        if (...) {
            resolve();
        } else {
            reject();
        }
    });
}
    
06.09.2017 / 23:19