What can ES6 Classes provide, as a pattern of organization, to asynchronous code. Below is an example with ES7 async/await, can an ES6-class have an asynchronous method, or
This is a late response, but the reason your second example doesn't work is because of a context error. When you pass a function () {} as an argument to Promise.prototype.then(), the lexical this inside the function will be the function itself, and not the class. This is why setting this.res seems to do nothing: this, in that case, refers to the function's own scope.
There are several ways of accessing an outer scope in Javascript, the classic one (that you see abundantly in ES5 code) being:
class Foo {
constructor() {
var _this = this
getHTML().then(function (res) {
_this.res = res
})
}
}
By making a reference to the class this, you can access it in inner scopes.
The ES6 way of doing it is to use arrow functions, which do not create a new scope, but rather "keep" the current one.
class Foo {
constructor() {
getHTML().then(res => this.res = res)
}
}
Aside from context concerns, this is still not an optimal asynchronous pattern in my opinion, because you've got no way to know when getHTML() has finished, or worse, has failed. This problem is solved elegantly with async functions. Though you cannot make an async constructor () { ... }, you can initiate a promise in the constructor, and await it in the functions that depend on it.
Example gist of an async property in a class constructor.