这个问题在这里已经有了答案:
How to access the correct `this` inside a callback
(13 个回答)
12 个月前关闭。
通常在使用 Promise 语法时,以下语法会产生相同的结果:
// Syntax A - works fine
getUser(id).then((user) => console.log(user)
// Syntax B - works fine
getUser(id).then(console.log)
然而,当我们在 Express 路由中尝试这样做时,只有语法 A 有效:// 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)
})
语法 B 产生错误: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)
为什么这不像第一个例子那样工作?
最佳答案
原因是因为response.json
是函数that looks up app
on this
.当你通过 res.json
你正在通过json
没有对它来自的对象的任何引用,所以它的 this
是(最有可能)undefined
)。 this
JavaScript 是动态绑定(bind)的,而不是像 C# 或 Java 这样的语言中的静态绑定(bind)。console.log
另一方面不使用 this
因此不受您如何调用它的影响。
我们可以自己构建这样的东西:
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!
关于javascript - 为什么不能使用这种 promise 语法快速发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69056090/