A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Async/await for class and object methods

trusktr
2015-11-09

Will we be able to make methods on a class or object async? For example:

class Foo {
  constructor() {...}

  async someMethod() {
    await someThing()
    return await somethingElse()
  }
}

(async () => {
  let f = new Foo()
  let result = await f.someMethod()
  console.log(result)
})()
trusktr
2015-11-09

Looks like so! Babel’s async-to-generator converts the Foo class to this generator-based version:

	        var Foo = (function () {
	            function Foo() {
	                _classCallCheck(this, Foo);
	            }

	            _createClass(Foo, [{
	                key: 'someMethod',
	                value: (function () {
	                    var ref = _asyncToGenerator(function* () {
	                        yield someThing();
	                        return yield somethingElse();
	                    });

	                    return function someMethod() {
	                        return ref.apply(this, arguments);
	                    };
	                })()
	            }]);

	            return Foo;
	        })();
marcosc
2015-11-15

yes, you should be able to do the above (as per Bable). Async arrow functions might not be a thing tho, but I’m not sure. I would recommend asking here: https://github.com/tc39/ecmascript-asyncawait