问题描述
我只使用纯JS和HTML。没有框架。
我正在将一些html文件提取到我的index.html中。提取完所有内容后,我想继续执行脚本。我正在尝试找出如何解决这个问题(我想是Promises),但是无法使其工作。如何等待所有人完成?
int tasks(15);
int threads(8);
int thread_index(0);
for( int i = 0 ; i < tasks; i++){
set( thread_index,i ); // pseudo code to start the task
thread_index = ( thread_index+1 ) % threads;
}
但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
正确的方法是什么?
解决方法
尝试更换
await Promise.all([prepareHead,prepareHeader,prepareFooter,prepareStaticLinks]);
console.log("document prepared");
使用
Promise.all([prepareHead,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,prepareStaticLinks]);
// next line should be called only after all files are fetched
console.log("document prepared");
};
getData();