Today, I was quite surprised by something that I came across. Within a bunch of express route handlers, I found some code snippets that looked like this (there are more function calls but for the sake of clarity, I've simplified it):
app.get('/api/foo', (req, resp) => {
Promise.resolve({one: 1})
.then(data=>resp.json(data))
})
As someone who considers themselves a proficient javascript programmer, I thought I could simplify the code by removing the anonymous function and calling resp.json
directly inside the then function:
app.get('/api/foo', (req, resp) => {
Promise.resolve({one: 1})
.then(resp.json)
})
However, when I attempted to do so, I encountered an issue where I never received a response and instead saw this error in the node console:
Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'app' of undefined
On the surface, it seems like .then(resp.json) and .then(data=>resp.json(data)) should be interchangeable. It appears to be a scope-related problem, but I would appreciate an explanation and possibly a workaround.