Sha*_*jan 2 javascript mongoose mongodb node.js async-await
以下代码完美运行:
const Course = mongoose.model('Course',courseSchema)
async function foo(){
const nodeCourse = new Course({
name: "Node JS Course",
author: "foo",
tags: ['node','backend']
})
const result = await nodeCourse.save()
console.log(result)
}
foo()
Run Code Online (Sandbox Code Playgroud)
但是这个给出了一个错误:
const Course = mongoose.model('Course',courseSchema)
(async ()=>{
const nodeCourse = new Course({
name: "Node JS Course",
author: "foo",
tags: ['node','backend']
})
const result = await nodeCourse.save()
console.log(result)
})()
Run Code Online (Sandbox Code Playgroud)
错误:
ObjectParameterError:Document()的参数"obj"必须是一个对象,得到异步函数
那么如何自动执行异步功能呢?
提前致谢
Cer*_*nce 10
这就是为什么当你不能100%确定ASI(自动分号插入)如何工作时你应该使用分号.(即使你了解ASI,你也许不应该依赖它,因为它很容易搞砸)
就行了
const Course = mongoose.model('Course',courseSchema)
(async ()=>{
// ...
})();
Run Code Online (Sandbox Code Playgroud)
因为之后没有分号('Course',courseSchema),并且由于下一行以a开头(,解释器会按如下方式解释您的代码:
const Course = mongoose.model('Course',courseSchema)(async ()=>{
Run Code Online (Sandbox Code Playgroud)
也就是说,你调用的结果mongoose.model('Course',courseSchema)与async功能(然后尝试调用的结果).
请改用分号,而不是依赖自动分号插入:
const Course = mongoose.model('Course',courseSchema);
(async ()=>{
const nodeCourse = new Course({
name: "Node JS Course",
author: "foo",
tags: ['node','backend']
});
const result = await nodeCourse.save();
console.log(result);
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
508 次 |
| 最近记录: |