4

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.

7
  • could you check the typescript version ? Commented Apr 6, 2018 at 9:36
  • Does it work when you remove the async token? Are you writing your program in Notepad? If so, try converting the EOL char. I had problems with node seeing it as illegal Commented Apr 6, 2018 at 9:44
  • 6
    did you try write this way : async test(){} ? Commented Apr 6, 2018 at 10:00
  • @fatemefazli Looks like that's fixed it. Thanks. Commented Apr 6, 2018 at 10:08
  • Apparently, according to the MDN doc, the async function test() { } syntax should be perfectly valid, though Commented Apr 6, 2018 at 10:12

2 Answers 2

4

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 () {
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer goes into more detail than mine about why it doesn't work. +1
1

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
}

1 Comment

Funnily enough I was getting the exact same error because I did not have the function tag. Adding it fixed the error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.