【问题标题】:Promises in mongoose [duplicate]猫鼬中的承诺[重复]
【发布时间】:2015-06-27 06:29:12
【问题描述】:

谁能解释一下为什么会这样:

// 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 似乎没有被调用。

【问题讨论】:

  • 你是否因为承诺而丢失了错误?点击末尾的 .catch():.then(res.json).catch(console.log);
  • 试试.then(res.json.bind(res)),因为您可能会丢失绑定上下文。
  • 这是关于 this 的工作方式,而不是承诺,绑定或包装在 lambda 中
  • @BenjaminGruenbaum:这不是重复的吗?我现在找不到它
  • 可能是“这在 JavaScript 中是如何工作的”,我在移动设备上

标签: javascript express mongoose promise


【解决方案1】:

res.json 确实希望作为方法调用,resthis 值。它适用于console.log,因为它已经绑定到节点中的console 对象。

你可以使用

.then(res.json.bind(res))

或继续使用该箭头功能。另见How to access the correct `this` context inside a callback?

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2012-12-14
    • 2017-06-15
    • 2019-06-04
    • 2017-08-18
    • 2018-02-15
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多