javascript 调用异步静态函数时出现 SyntaxError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46001392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:22:39  来源:igfitidea点击:

SyntaxError when calling an async static function

javascriptnode.jsasync-await

提问by NorTicUs

I'm playing a bit with async/await of Node 8.3.0 and I have some issue with static function.

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

MyClass.js

MyClass.js

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

index.js

索引.js

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

With this code I've got an SyntaxError: Unexpected tokenon MyClass. Why is that? Can't use a static function with awaitor have I made a mistake?

有了这个代码,我有一个SyntaxError: Unexpected tokenMyClass。这是为什么?不能使用静态函数await还是我犯了错误?

Thank you

谢谢

采纳答案by Endless

The await operator can only be used inside an async function.

await 运算符只能在异步函数中使用。

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

回答by Salketer

You cannot use await in the main script... Try this

您不能在主脚本中使用等待...试试这个

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

awaitcan only be used in an asyncfunction, and asyncfunction will return a promiseif not called with await.

await只能在async函数中使用,如果没有用 调用,async函数将返回一个。promiseawait