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
async/await can not be used in class method definition(without method body) · Issue #22035 · microsoft/TypeScript · GitHub.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With