Express and call response.json in a free point do not work in Promise.then

Today, something really surprised me. I came across a bunch of express route handlers, basically looking like this (there are more real function calls, but for the sake of readability:

app.get('/api/foo', (req, resp) => {
  Promise.resolve({one: 1})
    .then(data=>resp.json(data))
})

So, as a smart javascript programmer, I think I can get away from the anonymous function and just let the resp.json function function directly:

app.get('/api/foo', (req, resp) => {
  Promise.resolve({one: 1})
    .then(resp.json)
})

But when I try, I never get a response and see this in the node console:

Refusal from a raw promise (rejection id: 1): TypeError: Cannot read the property 'app' of undefined

.then(resp.json) . then (data = > resp.json(data)) . , , , , .

+4
2

, resp , , , json, resp.

resp.json then, resp . , then "" json resp. , .

, json - this, ( ) resp.

,

   Promise.resolve({one: 1})
    .then(resp.json.bind(resp))
+5

, this javascript.

, resp.json(data) this===resp, resp.json this===global.

, .then(resp.json.bind(resp)) ( ).

+3

Source: https://habr.com/ru/post/1662463/


All Articles