async function with the class in javascript

烈酒焚心 提交于 2020-04-10 09:20:47

问题


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

回答1:


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



回答2:


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;



回答3:


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


来源:https://stackoverflow.com/questions/53313507/async-function-with-the-class-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!