Why am I getting an Unexpected token async on node.js?

Viewed 53

Hi,

I have this code on my server file:

getName(){
    const promise = new Promise((resolve, reject) => {
        conn.query("SELECT name FROM members WHERE id=1", (err, res, fields) => {
            if (err) reject(err);

            resolve(res);
        });
    });
}

func() async {

    try{
        const data = await getName();
        console.log(data);
    } catch(e) {
        console.log(e);
    }
}

but I get this error: Unexpected token async so I removed async but then I get another error saying: Unexpected token {

What is happening here? I have node latest version: v10.24.1

Thank you.

2 Answers

The definition of your anonymous async function is wrong, try to change it like this example.

(async function() {
  // Your code
})();

Also, you didn't return the promise from your getName() function.

getName() {
  return new Promise((resolve, reject) => {
    // Your code
  })
}

More information about functions and async/await.

I think it is better if you use only async await and don't combine it with try and catch. That may give weird result. Try to refactor it only with async await syntax.

  async func(){
    const data = await getName();
    console.log(data);
}
Related