我只使用纯JS和HTML。没有框架。
我正在将一些html文件提取到我的index.html中。提取完所有内容后,我想继续执行脚本。我正在尝试找出如何解决这个问题(我想是Promises),但是无法使其工作。如何等待所有人完成?
const prepareHead = fetch("../static/_includes/_head.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("head").innerHTML = data;
resolve();
});
const prepareHeader = fetch("../static/_includes/_header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
const prepareStaticLinks = fetch("../static/_includes/_static_links.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("static_links").innerHTML = data;
});
const prepareFooter = fetch("../static/_includes/_footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
await Promise.all([prepareHead, prepareHeader, prepareFooter, prepareStaticLinks]);
// next line should be called only after all files are fetched
console.log("document prepared");
但await Promise
不起作用:Uncaught SyntaxError: await is only valid in async functions and async generators
正确的方法是什么?
尝试更换
await Promise.all([prepareHead, prepareHeader, prepareFooter, prepareStaticLinks]);
console.log("document prepared");
与
Promise.all([prepareHead, prepareHeader, prepareFooter, prepareStaticLinks])
.then(() => {
console.log("document prepared")
});
您的另一个选择是await
在async
函数内部使用,像这样
const getData = async () => {
const prepareHead = fetch("../static/_includes/_head.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("head").innerHTML = data;
resolve();
});
const prepareHeader = fetch("../static/_includes/_header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
const prepareStaticLinks = fetch("../static/_includes/_static_links.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("static_links").innerHTML = data;
});
const prepareFooter = fetch("../static/_includes/_footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
await Promise.all([prepareHead, prepareHeader, prepareFooter, prepareStaticLinks]);
// next line should be called only after all files are fetched
console.log("document prepared");
};
getData();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句