【问题标题】:SyntaxError when calling an async static function调用异步静态函数时出现语法错误
【发布时间】:2018-02-10 14:05:07
【问题描述】:

我在使用 Node 8.3.0 的 async/await 时遇到了一些静态函数的问题。

MyClass.js

class MyClass {
  static async getSmthg() {
    return true;
  }
}
module.exports = MyClass

index.js

try {
  const result = await MyClass.getSmthg();
} catch(e) {}

使用此代码,我在MyClass 上获得了一个SyntaxError: Unexpected token。 这是为什么? await 不能使用静态函数还是我犯了错误?

谢谢

【问题讨论】:

  • 你确实导入了 MyClass?
  • 您只能在async 函数中使用await。您是否使用函数包装来自index.js 的代码?
  • 忘记将其包装到 async 函数中。谢谢大家

标签: javascript node.js async-await


【解决方案1】:

如果您的节点或浏览器不支持顶级 await 并且它不作为模块运行,则只能在异步函数中使用 await 运算符。

你必须这样做

(async () => {
  try {
    const result = await MyClass.getSmthg();
  } catch(e) {}
})()

另一种方法是在 package.json 中设置 "type": "module"

【讨论】:

    【解决方案2】:

    你不能在主脚本中使用 await...试试这个

    async function test(){
        try {
          const result = await MyClass.getSmthg();
          return result;
        } catch(e) {}
    }
    test().then(function(res){console.log(res)})
    

    await 只能在async 函数中使用,而async 函数如果不与await 一起调用,将返回promise

    【讨论】:

    • erm,更正:您可以在“主”脚本中使用 await...但它只能在异步函数中使用。
    • 是的,也许我的措辞不是那么好……我的主脚本是指直接在全局范围内执行的代码……也就是不在函数中。
    • @Salketer 随时编辑您的答案,使其正确无误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    相关资源
    最近更新 更多