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 constructor in ES7?
Can I do:
class Foo {
async constructor() {
let res = await getHTML();
this.res = res
}
}
And, if not how should a constructor work that does this?
class Foo {
constructor() {
getHTML().then( function (res) {
this.res = res
}
}
}
If neither of these patterns work, can a constructor (and moreover classes) in an ES6 class
support any form of asynchronicity that operates on the object's state? Or, are they only for purely synchronous code bases? The above examples are in the constructor, but they don't need to be.. Pushing the problem down one more level..
class Foo {
myMethod () {
/* Can I do anything async here */
}
}
Or, with a getter...
class Foo {
get myProp() {
/* Is there any case that this is usefully asynchronous */
}
}
The only examples I could think of is to run something in parallel inside of the same method/constructor/getter, but to have the whole thing resolve before conclusion. I'm just confused because it seems with all the push to fully asynchronous libraries, this just serves to confuse things. Except for textbook examples, I can't find one application they're useful for.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…