title: How to pass async function value to an event handler
body: <p>I'm fetching the stylesheet and replacing all CSS variables with the actual hex value it corresponds to when the user changes the color as desired.</p>
  
  <p>I created an event handler so that when the user clicks the download button, all of the colors he/she selected, would be saved in the stylesheet at that moment, but it doesn't seem to work. I know it's an issue with my understanding of promises as a whole and <code>async await</code></p>
  
  <p><strong>What I did.</strong></p>
  
  <pre><code>const fetchStyleSheet = async () =&gt; {
    const res = await fetch("./themes/prism.css");
    const orig_css = await res.text();
    let updated_css = orig_css;
  
    const regexp = /(?:var\(--)[a-zA-z\-]*(?:\))/g;
    let cssVars = orig_css.matchAll(regexp);
    cssVars = Array.from(cssVars).flat();
    console.log(cssVars)
  
    for await (const variable of cssVars) {
      const trimmedVar = variable.slice(6, -1)
      const styles = getComputedStyle(document.documentElement)
      const value = String(styles.getPropertyValue(`--${trimmedVar}`)).trim()
  
      updated_css = updated_css.replace(variable, value);
    }
    console.log(updated_css)
  
    return updated_css
  }
  
  const main = async () =&gt; {
    const downloadBtn = document.getElementById('download-btn')
    downloadBtn.addEventListener('click', () =&gt; {
      const updated_css = fetchStyleSheet()
      downloadBtn.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(updated_css))
      downloadBtn.setAttribute('download', 'prism-theme.css')
    })
  }
  
  main()
  </code></pre>
  
  <p>I can't <code>await</code> the <code>updated_css</code> because it falls into the callback of the click event, which is a new function. </p>
  
  <p>Then I did the following thinking it would work since it was top level. </p>
  
  <pre><code>const downloadBtn = document.getElementById('download-btn')
  downloadBtn.addEventListener('click', async () =&gt; {
    const updated_css = await fetchStyleSheet()
    downloadBtn.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(updated_css))
    downloadBtn.setAttribute('download', 'prism-theme.css')
  })
  </code></pre>
  
  <p>That gave me the following error <code>TypeError: NetworkError when attempting to fetch resource.</code></p>
  
  <p>I understand that calling <code>fetchStyleSheet()</code> only returns a promise object at first and to get the value (which is <code>updated_css</code>),  I need to follow it with <code>.then()</code> or <code>await</code> it. </p>