首页 > 解决方案 > 无法在 Cloud9 上的节点上创建异步方法

问题描述

我正在移植一些我在浏览器中编写的代码,发现我似乎无法在 NodeJS 中创建异步方法

class Test{
    async hello(){
        return "hello";
    }
}

(async function(){
    let test = new Test();
    let hello = await test.hello();
    console.log(hello);
})();

当我执行这个时,我得到一个错误:

/home/ubuntu/workspace/test.js:2
    async hello(){
          ^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
    at ontimeout (timers.js:386:14)
    at tryOnTimeout (timers.js:250:5)

这在节点中是不可能的,还是我在这里没有什么不正确的?

我在跑步Node 8.x

标签: node.jsclassasync-awaitcloud9

解决方案


该代码中发生的错误如下:

let hello = await test.hello();
                  ^^^^

SyntaxError: Unexpected identifier

发生这种情况是因为您在函数await之外使用关键字。async

文档

await 运算符用于等待 Promise。它只能 在异步函数内部使用

class Test{
    async hello(){
        return "hello";
    }
}


(async() => {
  // You can only use `await` inside async function
  let test = new Test();
  let hello = await test.hello();
  console.log(hello);
})();


Is this just not possible in node, or am I don't something incorrect here? 
I am running Node 8.x

Nodeasync/await从 7.6 版本开始支持,所以你可以自由使用。

更新:

如果你得到:

async hello(){
      ^^^^^

SyntaxError: Unexpected identifier

这意味着您正在运行较旧的节点版本。尝试

console.log(process.version);

并且会 100% 打印低于 7.6 的版本。

您的 cli 上可能有节点 8.x,但 cloud9 上没有,要更新 cloud9 中的节点,请检查以下问题:


推荐阅读