猫鼬的承诺

安德烈·罗斯卡(Andrei Rosca)

任何人都可以解释为什么:

// 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章