Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 651
Dark Knight Avatar asked Nov 15 '18 06:11

Dark Knight


People also ask

Can a class method be async JavaScript?

async/await can not be used in class method definition(without method body) · Issue #22035 · microsoft/TypeScript · GitHub.

Can a JavaScript class constructor be async?

The static async factory function pattern allows us to emulate asynchronous constructors in JavaScript. At the core of this pattern is the indirect invocation of constructor . The indirection enforces that any parameters passed into the constructor are ready and correct at the type-level.

What is async function in JavaScript?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

How do you call async function?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


1 Answers

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
like image 83
Aniket Pawar Avatar answered Sep 22 '22 15:09

Aniket Pawar