【发布时间】: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