阅读我看到的文档;
Mongoose异步操作,如.save()和查询,返回ES6 promise。
以为我熟悉ES6的承诺,所以我写了这样的东西:
newUser.save().then(user =>
res.json({
id: user.id,
name: user.name,
email: user.email
})
)
.catch(
(err = res.status(500).json({
server: 'Something went wrong, please try again soon'
}))
);
我测试并找到一个成功附加到数据库,但无论如何调用500。记录的错误如下:
(node:40071) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
使用堆栈跟踪,而且:
(node:40071) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:40071) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我正在挠头,并参考规范,Promise docs。
我很困惑为什么这会引发错误,因为我觉得我很清楚地处理错误。而且,当我一起删除catch语句时,所有错误似乎都消失了!就像发生了什么?