Monday, 17 April 2017

Strange async/await behaviour in a class

Node 7.9.0

This is the scenario:

class TestClass {
  constructor() {
    const x = await this.asyncFunc()
    console.log(x)
  }
  async asyncFunc() {
    return new Promise((accept) => {
      setTimeout(() => accept("done"), 1000)
    })
  }
}
new TestClass()

The error is Unexpected token this on line 3

OK, so I wrap it up like this... const x = await (this.asyncFunc())

Now I get await is not defined

It makes me think that node 7.9.0 has no idea about await/sync despite http://node.green/ telling me it is supported and it's example is running just fine.

(function(){
(async function (){
  await Promise.resolve();
  var a1 = await new Promise(function(resolve) { setTimeout(resolve,800,"foo"); });
  var a2 = await new Promise(function(resolve) { setTimeout(resolve,800,"bar"); });
  if (a1 + a2 === "foobar") {
    console.log("passed")
  }
}());
})()



via Jake Cattrall

No comments:

Post a Comment