为什么这两个函数调用彼此不相等?
Why are these two function calls not equal to each other?
抱歉,如果标题含糊不清,我不确定如何更好地解释它。
为什么在这种情况下使用匿名函数调用有效:
Team
.findAll()
.then(function(teams) {
res.send(teams);
});
但是将 res.send
直接传递给 .then()
,它不起作用:
Team
.findAll()
.then(res.send);
这会导致此错误:
Possibly unhandled TypeError: Cannot read property 'method' of undefined
at res.send (/opt/web/projects/node_modules/express/lib/response.js:83:27)
at Promise._settlePromiseAt (/opt/web/projects/node_modules/sequelize/lib/promise.js:76:18)
at process._tickCallback (node.js:442:13)
这两个不是相等的吗? res.send
只接受一个参数,所以它不像是将一些奇怪的未知参数传递给函数。
.then()
方法希望您向它传递一个函数,因为它(最终)会调用它。如果你只是传递一个(非函数)值,那是不可能发生的。
调用.then()
的意义在于,"when the operation has finished, please do this."
edit — 啊好的,抱歉。在这种情况下,问题是当您传递 res.send
时,send
方法将丢失上下文。也就是说,当 Promise 机制调用 send
函数时,它不会知道 res
.
的值
你可以这样做:
.then(res.send.bind(res))
通过这样做,您可以确保当 send
最终被调用时,它将被调用使得 this
将成为对您的 res
对象的引用。
抱歉,如果标题含糊不清,我不确定如何更好地解释它。
为什么在这种情况下使用匿名函数调用有效:
Team
.findAll()
.then(function(teams) {
res.send(teams);
});
但是将 res.send
直接传递给 .then()
,它不起作用:
Team
.findAll()
.then(res.send);
这会导致此错误:
Possibly unhandled TypeError: Cannot read property 'method' of undefined
at res.send (/opt/web/projects/node_modules/express/lib/response.js:83:27)
at Promise._settlePromiseAt (/opt/web/projects/node_modules/sequelize/lib/promise.js:76:18)
at process._tickCallback (node.js:442:13)
这两个不是相等的吗? res.send
只接受一个参数,所以它不像是将一些奇怪的未知参数传递给函数。
.then()
方法希望您向它传递一个函数,因为它(最终)会调用它。如果你只是传递一个(非函数)值,那是不可能发生的。
调用.then()
的意义在于,"when the operation has finished, please do this."
edit — 啊好的,抱歉。在这种情况下,问题是当您传递 res.send
时,send
方法将丢失上下文。也就是说,当 Promise 机制调用 send
函数时,它不会知道 res
.
你可以这样做:
.then(res.send.bind(res))
通过这样做,您可以确保当 send
最终被调用时,它将被调用使得 this
将成为对您的 res
对象的引用。