Node: async await for class method

Created on 4 Mar 2017  路  5Comments  路  Source: nodejs/node

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 () => {

}

}
  • Version: v7.7.1
  • Platform:
    Linux moch 3.19.0-31-generic #36~14.04.1-Ubuntu SMP Thu Oct 8 10:21:08 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

Most helpful comment

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);
})()

All 5 comments

How you resolved the issue?

@marcoacierno Updating to Node.js v8.x will fix this issue.

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vsemozhetbyt picture vsemozhetbyt  路  3Comments

cong88 picture cong88  路  3Comments

addaleax picture addaleax  路  3Comments

willnwhite picture willnwhite  路  3Comments

srl295 picture srl295  路  3Comments