Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
How Callbacks access Methods

I am wondering how are we able to use res.render inside a callback

function getUsers(cb){
  fs.readFile('data.json', 'utf8', (err, data) => {
    if (err) return cb(err);
    const users = JSON.parse(data);
    return cb(null, users);
  });
}

app.get('/', (req,res) => {
  getUsers((err,users) =>{
    if(err){
      res.render('error', {error:err})
    } else{
      res.render('index', {title: "users", users: users.users});
    }
  })
}); 

Because when we pass the callback, Callstack gets loaded up with getUsers(cb) Function, and we are no longer inside the route, then how the callback is using the res.render Method? And how do I know moving forward, which values is accessible to callbacks?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inline functions/callbacks like you're using here can see the parent function scope and all of it's variables and arguments. This is referred to as the "lexical scope".

If the callback was not inline, then it couldn't see those variable/arguments because the function would be declared in a different scope.

So, this is why the inline callback for readFile() you've declared can access cb(...) and similarly why the inline callback you pass to getUsers() can access req and res. Those are all arguments in the parent scope.

Note, the access to these parent variables/arguments is not from the call stack. This is from the lexical scope.


This access to res.render() only works because the function is declared inside the lexical scope where res is accessible. If your route was declared like this instead:

function getUsersCallback(err, users) {
    if(err){
      res.render('error', {error:err})
    } else{
      res.render('index', {title: "users", users: users.users});
    }
}

app.get('/', (req,res) => {
  getUsers(getUsersCallback);
}); 

Then this would not work because the callback function is not declared in a lexical scope which has access to req and res.


Keep in mind that function arguments and local variables in Javascript are stored in scope objects, not on the call stack like they would be in a language like C/C++. This is for a bunch of reasons, not the least of which is the lifetime of a function scope may extend beyond when the function returns (due to closures) and so that scopes can be chained so the interpreter can lookup things in the parent scope (in order to implement the "lexical scope" that the language implements).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda