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

178
Visualizações
Why can't express send using this promise syntax?

Normally when using Promise syntax, the below syntaxes produce the same result:

// Syntax A - works fine
getUser(id).then((user) => console.log(user)

// Syntax B - works fine
getUser(id).then(console.log)

Yet when we attempt this in an Express route, only syntax A works:

// Works
app.get('/syntax_a', (req, res) => {
  getUser(req.body.id).then((user) => res.json(user))
})

// Fails
app.get('/syntax_b', (req, res) => {
  getUser(req.body.id).then(res.json)
})

Syntax B yields an error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'app' of undefined
    at json (/server/node_modules/express/lib/response.js:256:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Why isn't this working like the first example?

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

0

The reason is because response.json is a function that looks up app on this. When you pass res.json you're passing json without any reference to the object it comes from so its this is (most likely) undefined). this in JavaScript is dynamically bound, rather than statically bound as it is in a language like C# or Java.

console.log on the other hand doesn't use this and so isn't affected by how you call it.

We can build something like this ourselves:

let _privateImplementation = (...args) => console.log(...args);

let ourPrivateBoundExample = {
  doIt(some, info) {
    _privateImplementation("Doing it", some, info);
  }
}

ourPrivateBoundExample.doIt(1, 2); // Doing it 1 2
Promise.resolve("Hello there!")
  .then(ourPrivateBoundExample.doIt) // Doing it Hello there!
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