Auto-execute async function

强颜欢笑 提交于 2020-12-12 04:34:37

问题


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


回答1:


This 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);
})();


来源:https://stackoverflow.com/questions/52675041/auto-execute-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!