[英]How to return the value from an async function
我有一个异步函数,我想从中返回一个值然后使用。
在updatedStyleSheet
函数中,我想返回updated_css
以便我可以在其他地方使用它。
async function updatedStyleSheet() {
const res = await fetch("./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();
for (const v of cssVars) {
updated_css = updated_css.replace(v, colors[v.slice(6, -1)]);
};
// return updated_css ?
}
如果我调用这个函数,我会得到一个 Promise 对象。 理所当然,因为异步函数总是返回一个承诺。
我可以在updatedStyleSheet
函数中返回updated_css
并在之后做类似的事情吗?
const newSheet = updatedStyleSheet().then(css => css)
然后在我的脚本中的任何地方使用newSheet
变量?
最终目标
获取包含我的 CSS 文本内容的updated_css
并将其用作href
值,以便用户可以下载样式表。
编辑
我尝试添加一个事件处理程序,以便用户保存后所有选定的颜色值都将保存在样式表中,但它似乎不起作用。 我知道这仍然是我对 Promise 的整体理解的问题。
我做了什么。
const updatedStyleSheet = 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 = updatedStyleSheet()
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 updatedStyleSheet()
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.
我会使用 .then() 函数 EX 来折叠承诺:
var bar = updatedStyleSheet()
bar.then(updated_css=>{
//logic goes here
});
是的。 由于您已经在使用async/await
,因此只需创建一个顶级async
函数,例如main
,并在等待解决的承诺后使用返回的updated_css
内容:
async main() {
const updated_css = await updatedStyleSheet()
// use css as you please
}
// run program
main()
不要介意再调用一次函数的成本。
如果您需要等待异步函数返回一个值(以便以后可以使用该值),请使用await
关键字:
const newSheet = await updatedStyleSheet()
但是,请注意等待会阻止执行,直到函数返回。 这可能不是您想要的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.