【问题标题】:async function with the class in javascriptjavascript中类的异步函数
【发布时间】:2019-04-18 04:54:54
【问题描述】:

我在 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

我需要做的是将上述函数转换为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

【问题讨论】:

    标签: javascript node.js asynchronous async-await ecmascript-2017


    【解决方案1】:

    您可以简单地在函数名称前添加 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
    

    【讨论】:

    • 是的,这会起作用,但这不是 ES-7 语法。我说的对吗?
    • @DarkKnight 异步函数在 ES2017 中被引入。如果你使用的是 es6,那么你需要使用 babel 或 webpack 编译它
    • 这是我的.babelrc { "presets": [ ["env", { "targets": { "node": 4.3 } }] ], "env": { "test": { "plugins": ["istanbul"] } } } 你能告诉我我在这里缺少什么吗?
    • 您能详细介绍一下您当前使用的 ecmascript 和 Node 版本吗?
    • 节点版本v8.9.3 和我如何检查这个version of ecmascript
    【解决方案2】:

    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;
    

    【讨论】:

    • OP 并没有尝试将async 用作函数,而是将其用作关键字。再看一遍:sendNotification = async (/* args */) => {
    • 啊,是的,手机屏幕窄了。
    【解决方案3】:
    class Foo {
        x = something
    }
    

    此作业是类字段的示例。 class property / class field 语法的使用目前处于 TC39 进程的第 3 阶段,这意味着它还没有出现在 ECMAScript 中,并且还没有被所有 JS 引擎原生支持。它可以通过 Babel 等转译器使用,但前提是您自己配置和运行这样的转译器。

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

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

    【讨论】:

    • 这是我的.babelrc { "presets": [ ["env", { "targets": { "node": 4.3 } }] ], "env": { "test": { "plugins": ["istanbul"] } } } 你能告诉我我在这里缺少什么吗?
    猜你喜欢
    • 2021-06-22
    • 2017-08-01
    • 2022-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    相关资源
    最近更新 更多