Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async function inside a class

I get this error when I try to run an async function described in a class

masterClass.js

class MasterClass{

  async function updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}

test.js

const MasterClass =  require('./MasterClass.js')
let m = new MasterClass()
m.updateData(a, b)

Error

async function updateData(a, b){
                 ^^^^^^^^^^
SyntaxError: Unexpected identifier
like image 314
Leo Avatar asked Dec 06 '17 10:12

Leo


People also ask

Can a class have an async function?

Async Option ConstructorThe async function call can be added right into the class instantiation step, without needing a separate init() call or having to modify your established method of class construction.

Can you have an async function inside an async function?

async and awaitInside 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.

How does async await work internally?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.


1 Answers

You dont need function as pointed out by @dfsq in the comments

Then you have to use module.exports or export to exposed your class as a module.

masterclass.js

module.exports = class MasterClass{

  async updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}
like image 83
Stamos Avatar answered Oct 14 '22 09:10

Stamos