javascript 中 class 的异步函数

async function with the class in javascript

我已经在 nodejs

中创建了一个 class
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

我需要做的是将上面的函数转换为async。但是当我使用下面的语法时它会抛出错误

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

               ^

语法如下

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

您可以简单地在函数名称前添加 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
class Foo {
    x = something
}

此分配是 class 字段的示例。 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的用法,但前提是你自己配置和运行这样的转译器。

幸运的是你不需要 class 字段语法来使 class 方法异步,你可以只使用 async 关键字。

class Foo {
    async myMethod () {/* ... */}
}

async是指定异步函数的关键字,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;