13

I have create a class in nodejs

class ApnService {
  sendNotification(deviceType, deviceToken, msg, type, id) {
    try {
      const note = await apnProvider.send(note, deviceToken)
      console.log(note)
    } catch (err) {
      console.log(err)
    }
  }
}

export default ApnService

What I need to do is to convert above function to async. But when I use below syntax It throws me error

SyntaxError: src/services/apn.js: Unexpected token (43:19)
  41 |   }
  42 | 
> 43 |   sendNotification = async(deviceType, deviceToken, msg, type, id) => {
     | 

               ^

Below is the syntax

class ApnService {
  sendNotification = async(deviceType, deviceToken, msg, type, id) => {
    try {
      const note = await apnProvider.send(note, deviceToken)
      console.log(note)
    } catch (err) {
      console.log(err)
    }
  }
}

export default ApnService
Dark Knight
  • 995
  • 4
  • 22
  • 48

3 Answers3

19

You can simply add async before function name to declare that function as async,

class ApnService {
  async sendNotification(deviceType, deviceToken, msg, type, id) {
    try {
      const note = await apnProvider.send(note, deviceToken)
      console.log(note)
    } catch (err) {
      console.log(err)
    }
  }
}

export default ApnService
Aniket Pawar
  • 2,641
  • 19
  • 32
3

async is a keyword to designate an asynchronous function, try

class ApnService {
    async sendNotification(deviceType, deviceToken, msg, type, id) { 
        try { 
            const note = await apnProvider.send(note, deviceToken) 
            console.log(note) 
        } catch (err) { 
            console.log(err) 
        } 
    }
 }
export default ApnService;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1
class Foo {
    x = something
}

This assignment is an example of a class field. The usage of class property / class field syntax is currently at stage-3 in the TC39 process, meaning it is not yet in ECMAScript and not yet supported natively by all JS engines. It can be used via transpilers like Babel, but only if you configure and run such a transpiler yourself.

Luckily you don't need class field syntax to make a class method async, you can just use the async keyword.

class Foo {
    async myMethod () {/* ... */}
}
Gabriel L.
  • 1,629
  • 1
  • 17
  • 18
  • This is my `.babelrc` `{ "presets": [ ["env", { "targets": { "node": 4.3 } }] ], "env": { "test": { "plugins": ["istanbul"] } } } ` Could you please let me know what I am missing here? – Dark Knight Nov 15 '18 at 06:45