自动执行异步功能 [英] Auto-execute async function

查看:128
本文介绍了自动执行异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可完美运行:

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

错误:

ObjectParameterError:Document()的参数"obj"必须是一个对象,具有异步功能

ObjectParameterError: Parameter "obj" to Document() must be an object, got async function

那么我该如何自动执行异步功能?

So how can I auto-execute an async function?

预先感谢

推荐答案

这就是为什么当您不确定100%知道ASI(自动分号插入)如何工作时应该使用分号的原因. (即使您了解ASI,也可能不应该依赖它,因为它很容易弄乱)

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)

在线

const Course = mongoose.model('Course',courseSchema)
(async ()=>{
  // ...
})();

因为在('Course',courseSchema)之后没有分号,并且由于下一行以(开头,所以解释器将您的代码解释如下:

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 ()=>{

也就是说,您正在使用async函数调用 mongoose.model('Course',courseSchema)的结果(然后尝试调用结果).

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

这篇关于自动执行异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆