nick.cook
nick.cook

Reputation: 2141

TypeScript - 'Unexpected token' for async function prefix

I'm receiving an 'Unexpected token' error in typescript where I'm trying to write an async function like this:

async function test() {
  ...
}

I've seen that this can be caused due to running an older version of node that doesn't support async function syntax, but mine was running version 8.

Just to remove any possibility of my node version not supporting this, I've just updated to version 9.11.1, checked that this is being used in the command line, and the async prefix is still returning the unexpected token error.

Upvotes: 4

Views: 1948

Answers (2)

Jacob
Jacob

Reputation: 78840

That syntax is fine:

async function foo() {
    throw new Error('Just an example');
}

...but if you're trying to use it in a context where the function keyword is invalid, it won't compile, and it's not even valid JavaScript. For example, these are not valid:

class Foo {
  async function foo() {
    // Syntax error!
  }
}
const blah = {
  async function foo() {
    // Syntax error!
  }
}

async function used in this way is fine for declaring a function but not for defining methods. For methods, you'll want to omit the function keyword:

class Foo {
  async foo() {
  }
}
const blah = {
  async foo() {
  }
}

...or use a function expression:

const blah = {
  foo: async function () {
  }
}

Upvotes: 4

Marsroverr
Marsroverr

Reputation: 747

Still running into this as of Node 12.16.3

The solution is to remove the function tag and use the following syntax:

async test() {
  // Function body
}

Upvotes: 1

Related Questions