任何人都可以解释为什么:
// this works
router.route('/videos')
.get((req, res)=>{
Video.find()
.exec()
.then(console.log);
});
// this also works
router.route('/videos')
.get((req, res)=>{
Video.find()
.exec()
.then(videos=>{
res.json(videos)
});
});
可以,而且:
router.route('/videos')
.get((req, res)=>{
Video.find()
.exec()
.then(res.json);
});
不是吗
该res
对象表示Express.js应用在收到HTTP请求时发送的HTTP响应。该console.log
方法输出视频数据,而res.json
似乎没有被调用。
res.json
不希望被称为一种方法,与res
作为this
价值。console.log
之所以可以使用它,是因为它已经绑定到console
节点中的对象。
您可以使用
.then(res.json.bind(res))
或继续使用该箭头功能。另请参见如何在回调中访问正确的`this`上下文?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句