Cloud9环境下Node.js 8.x无法创建async类方法的问题咨询
问题分析与解决
你遇到的错误不是Node.js 8.x不支持类中的异步方法,而是一个很容易忽略的JavaScript语法细节——**自动分号插入(ASI)**导致的解析错误!
问题根源
你的代码里,class Test {...}定义结束后没有添加分号,紧接着的立即执行函数(async function(){...})()会被JavaScript解析器误认为是要调用这个class(相当于写了class Test{}()),而class本身不能直接被调用(必须用new实例化),因此抛出了SyntaxError: Unexpected identifier。
修正后的代码
只需要在class定义末尾加上分号,或者在立即执行函数前添加分号隔开即可:
class Test { async hello() { return "hello"; } }; (async function() { let test = new Test(); let hello = await test.hello(); console.log(hello); })();
或者另一种写法(在立即执行函数前加分号,避免ASI问题):
class Test { async hello() { return "hello"; } } ;(async function() { let test = new Test(); let hello = await test.hello(); console.log(hello); })();
补充说明
Node.js 8.x完全支持ES2017的异步函数(包括作为类方法)——async/await在Node.js 7.6.0就已经默认启用,8.x作为LTS版本自然兼容这个特性。你遇到的只是一个常见的语法疏漏,并非环境不支持。
内容的提问来源于stack exchange,提问作者Jefferey Cave
相关产品推荐
相关产品推荐

