Javascript 自动执行异步函数
下面的代码非常有效:Javascript 自动执行异步函数,javascript,node.js,mongodb,mongoose,async-await,Javascript,Node.js,Mongodb,Mongoose,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() cons
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()
但这一条给出了一个错误:
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)
})()
错误:
ObjectParameterError:Document()的参数“obj”必须是一个对象,并且是一个异步函数
那么如何自动执行异步函数呢
提前感谢这就是为什么当您不能100%确定ASI(自动分号插入)的工作原理时,应该使用分号的原因。(即使你理解ASI,也不应该依赖它,因为它很容易搞糟) 在线上
const Course = mongoose.model('Course',courseSchema)
(async ()=>{
// ...
})();
因为('Course',courseSchema)
后面没有分号,而且因为下一行以(
)开头,所以解释器对代码的解释如下:
const Course = mongoose.model('Course',courseSchema)(async ()=>{
也就是说,您正在使用async
函数调用mongoose.model('Course',courseSchema)
的结果(然后尝试调用结果)
请改用分号,而不是依赖自动插入分号:
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);
})();