2
I would like to have access to the value of a variable returned from a callback outside of the callback function, and I would also like to understand why there is no syntax error when I try to use a variable that does not exist within the scope of the callback function. I created the example below to demonstrate:
var armazenarValor
var meuObj = {
espera: function(valor, callback){
setTimeout(()=>{
callback(valor)
},2000)
}
}
meuObj.espera("valorQualquer", (valor)=>{
armazenarValor = valor
variavelQueNaoExiste = 'Eu não existo'
console.log(variavelQueNaoExiste)
})
console.log(armazenarValor)
The value of my variable armazenarValor
is undefined
, but I would like it to keep the value of the parameter valor
, for me to use in other parts of the code.
And the variable variavelQueNaoExiste
is not declared in any part of the code, but still it works.
I did a test playing everything within an async function and using the await operator to see if it would be possible to have the updated value of
armazenarValor
but it still didn’t. What I would really like is to have access to the updated value ofamazenarValor
without only being inside the callback function.– Fábio Junio Alves Sousa
@Fábiojunioalvessousa you really have to use the value inside the callback. You can use
async/await
but in that case you have to have a trial and a callback for the.then
anyway...– Sergio
I’ve added read links to the answer so you can read more about it.
– Sergio
I created this example to illustrate the doubt I’m having with the use of an npm package, the use of it follows this structure there, as I have to use several methods and each method depends on the value returned from the previous method, I will end up creating a cascade of methods, So I wanted to try to write a "cleaner" code to avoid this cascading of methods. Regarding the use of the variable that was not declared in any part of the code, you can tell me why it works?
– Fábio Junio Alves Sousa
@Fábiojunioalvessousa creates a new question with the cascade code you want to correct if you need help. The first link I put at the end of the answer helps in this. Regarding
variavelQueNaoExiste
this is (unfortunately) possible in Javascript. But if you use mode Strict or good Eslint rules this accuses error.– Sergio
Thanks Sergio! The use of
'use strict'
makes it point error. I’ll give a read on the links you sent me first before creating a new question, thanks for the references!– Fábio Junio Alves Sousa