ParseError: Unexpected token


#1

Hi Team,

I have a Helper function,

async ucFirst(s) {
     return s.charAt(0).toUpperCase() + s.substr(1)
}

When I call this method inside a loop in my controller i’m getting the below error

  console.log(await this.AppHelper.ucFirst(elem));
                              ^
  ParseError: Unexpected token

Eg:

      var arr = ["apple", "pear", "orange"];
          arr.forEach(function (elem) {
            console.log(await this.AppHelper.ucFirst(elem));
      
        });

Please anyone can help me…??


#2

Try:

const fruit = await this.AppHelper.ucFirst(elem)
console.log(fruit)

#3

Thank you for your reply… :slightly_smiling_face:

If I call this method outside the loop, it is working perfectly.
but the problem is inside the loop.

This is how I need

      var arr = ["apple", "pear", "orange"];
       arr.forEach(function (elem) {
            console.log(await this.AppHelper.ucFirst(elem));
          });  

Expected Result : Apple , Pear, Orange


#4

Hey @sudhiN! :wave:

It’s because you are using the await keyword inside a non-async function.

You need to use a for...of loop.


#5

Thank you… :slightly_smiling_face: