Returning callback values in main function - JS/Nodejs

Asked

Viewed 1,659 times

1

I have a primary function and a callback function within it. I need that depending on the callback return my main function return 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 do this? I have tried to declare a variable in the scope of the main function and modify it within the callback but without success.

  • You need to catch the return of funcaoPrincipal where is it called? Something like: const retorno = funcaoPrincipal()? I’m not sure I quite understand what you want.

  • I just need to return something to the main function depending on the situation of the callback, if I use a Return inside the callback it will not return in the main function.

1 answer

2


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 run asynchronously, it will still not be available just 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 that, 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();
        }
    });
}

Browser other questions tagged

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