如何将异步函数值传递给事件处理程序

时间:2020-01-19 15:13:22

标签: javascript promise async-await dom-events

我正在获取样式表,并将所有CSS变量替换为与用户根据需要更改颜色时对应的实际十六进制值。

我创建了一个事件处理程序,以便当用户单击下载按钮时,他/她选择的所有颜色都将被保存在样式表中,但是似乎不起作用。我了解整个承诺和async await

的问题

我做了什么。

const fetchStyleSheet = async () => {
  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 () => {
  const downloadBtn = document.getElementById('download-btn')
  downloadBtn.addEventListener('click', () => {
    const updated_css = fetchStyleSheet()
    downloadBtn.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(updated_css))
    downloadBtn.setAttribute('download', 'prism-theme.css')
  })
}

main()

我无法await updated_css,因为它属于click事件的回调,这是一个新功能。

然后我做了以下思考,因为它是顶级的,所以它可以工作。

const downloadBtn = document.getElementById('download-btn')
downloadBtn.addEventListener('click', async () => {
  const updated_css = await fetchStyleSheet()
  downloadBtn.setAttribute('href', 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(updated_css))
  downloadBtn.setAttribute('download', 'prism-theme.css')
})

这给了我以下错误TypeError: NetworkError when attempting to fetch resource.

我知道调用fetchStyleSheet()只会首先返回一个promise对象并获取值(即updated_css),我需要在其后跟随.then()或{{1} }。

0 个答案:

没有答案