简体   繁体   中英

async function with the class in javascript

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

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

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;
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 () {/* ... */}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM