The below code works perfectly:
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()
But this one gives an error:
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)
})()
Error:
ObjectParameterError: Parameter "obj" to Document() must be an object, got async function
So how can I auto-execute an async function?
Thanks in advance
The below code works perfectly:
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()
But this one gives an error:
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)
})()
Error:
ObjectParameterError: Parameter "obj" to Document() must be an object, got async function
So how can I auto-execute an async function?
Thanks in advance
Share Improve this question edited Oct 6, 2018 at 1:57 Shankar Thyagarajan asked Oct 6, 2018 at 1:46 Shankar ThyagarajanShankar Thyagarajan 91610 silver badges22 bronze badges1 Answer
Reset to default 16This is why you should use semicolons when you aren't 100% sure about how ASI (Automatic Semicolon Insertion) works. (Even if you understand ASI, you probably shouldn't rely on it, because it's pretty easy to mess up)
On the lines
const Course = mongoose.model('Course',courseSchema)
(async ()=>{
// ...
})();
Because there's no semicolon after ('Course',courseSchema)
, and because the next line begins with a (
, the interpreter interprets your code as follows:
const Course = mongoose.model('Course',courseSchema)(async ()=>{
That is, you're invoking the result of mongoose.model('Course',courseSchema)
with the async
function (and then attempting to invoke the result).
Use semicolons instead, rather than relying on Automatic Semicolon Insertion:
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);
})();