Skip to content

Instantly share code, notes, and snippets.

@koddsson
Last active April 26, 2019 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koddsson/e2338e6dc8d86d8f278dd7cc4587fb00 to your computer and use it in GitHub Desktop.
Save koddsson/e2338e6dc8d86d8f278dd7cc4587fb00 to your computer and use it in GitHub Desktop.

await in getter.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment