1

I am porting some code I wrote in the browser, and discovered I can't seem to create asynchronous methods in NodeJS

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

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

When I execute this, I get an error:

/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)

Is this just not possible in node, or am I don't something incorrect here?

I am running Node 8.x

Jefferey Cave
  • 2,507
  • 1
  • 27
  • 46

1 Answers1

3

The error that happens in that code is the following:

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

SyntaxError: Unexpected identifier

Which happens because you are using await keyword outside of an async function.

From the docs:

The await operator is used to wait for a Promise. It can only be used inside an async function.

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

Node supports async/await since version 7.6, so you can use it freely.

Update:

If you're getting:

async hello(){
      ^^^^^

SyntaxError: Unexpected identifier

It means you're running on an older node version. Try

console.log(process.version);

And will 100% print a version lower than 7.6.

You may have node 8.x on your cli, but not on cloud9, to update node in cloud9 check the following question:

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98