【发布时间】:2018-04-13 17:38:03
【问题描述】:
我有以下代码:
const checkForRecord = async (id) => {
let model = mongoose.model('User');
let query = {}
query.dummy = false; <== This is field is here to forcely cause an error, as it is not present on my User model.
let result = await model.findById(id, query);
console.log('Code reached here !!!');
console.log(result);
}
我收到以下错误:
(node:6680) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value ...
我的console.logs 甚至都没有被调用。
为什么没有设置错误,因为我的操作是异步的?
我都试过了:
let result = await model.findById(id, query);
和
let result = await model.findById(id, query).exec();
同样的行为。
【问题讨论】:
-
使用 async/await 您应该使用 try/catch 来处理
awaited 结果的错误,请参阅几乎所有关于 async/await 的教程以获取示例 .... 将结果设置为错误令人困惑,不是吗?你怎么知道结果是有效的还是错误的? -
该错误似乎表明您传递给
checkForRecord的任何内容,因为id不能转换为ObjectId,您能告诉我们您的id是什么吗? -
我认为 OP 是故意导致错误 - 看到这个 -
<== To cause an error, this field is not used -
const checkForRecord = async (id) {...是语法错误。代码实际上是什么样子的?箭头函数? -
@T.J.Crowder 我的话...
标签: javascript asynchronous mongoose async-await