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();
}
});
}
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.– Wiley Marques
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.
– Wesley Nascimento