Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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).

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda