Since you can't make getters async
in JavaScript classes it's impossible to do something like this:
class Foobar {
set src(url) {
this.src = url
await this.fetchResults() // Unexpected keyword since the function isn't marked as `async`
}
await fetchResults() {
const response = await fetch(this.src)
const html = await response.text()
this.results.innerHTML = html
}
}
Instead you can do something like this:
class Foobar {
set src(url) {
this.src = url
return this.fetchResults() // It's legal to use the `return` keyword here and it will block until the `fetchResults` method terminates.
}
await fetchResults() {
const response = await fetch(this.src)
const html = await response.text()
this.results.innerHTML = html
}
}
An even better way to do this is something like:
class Foobar {
set src(url) {
this.src = url
this.fetchResults() // No keyword
}
fetchResults() {
fetch(this.src).then(response => {
return response.text()
}).then(html => {
this.results.innerHTML = html
})
}
}
async
/await
is great but sometimes I guess we still need to use promises 😄
This is derived example but this happens a lot in Web Components where you use getter and setters a lot.