How to specify async class method in node.js 7.6 +
The following ways are breaking :
class A{
async abc(){
//
return 'abc';
}
}
and
class A{
async function abc(){
//
return 'abc';
}
}
gives error
async abc(ll){
^^^^
SyntaxError: Unexpected identifier
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
AND
return (async () => {
^
SyntaxError: Unexpected token (
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
for
abc(){
return (async () => {
}
}
How you resolved the issue?
@marcoacierno Updating to Node.js v8.x will fix this issue.
It seems we cannot have async constructors.
You can always use the factory Pattern as is a very common practice with this requirement.
class A {
constructor(fooVal) {
this.foo = fooVal;
}
}
class AFactory {
static async create() {
return new A(await Promise.resolve('fooval'));
}
}
(async function generate() {
const aObj = await AFactory.create();
console.log(aObj);
})()
@AyushG3112
class AFactory { static async create() { return new A(await Promise.resolve('fooval')); } }
This only makes the params to the constructor to be async
, not the constructor itself. An async constructor would pseudo-logic be what @dalu wrote:
class A {
constructor() {
this.foo = await externallib.create();
}
}
your answer doesn't work for that case.
Most helpful comment
You can always use the factory Pattern as is a very common practice with this requirement.