我有一个功能,可以打印出元素中的文本,然后打印出来自不同网页的元素中的文本。
function together(){
var finalString ="";
var x = document.getElementsByClassName("h-userinput");
for (var i = 0; i < x.length; i++) {
var text = x[i].innerText || x[i].textContent;
console.log(text+"\n");
var query = "#ctl00_ContentPlaceHolder_ResultsGrid_TB > tr:nth-child(bbcc) > td.total-score-column";
query = query.replace("bbcc",i+1);
var poop = ((document.querySelector(query)).onclick.toString());
text = poop.replace("javascript:location.href=\'","");
text = text.replace("function onclick(event) {","");
text=text.replace("}","");
text = text.replace("\';","");
text = "https://bartholomew.itslearning.com"+text;
var url = text;
fetch(url)
.then(res => res.text())
.then((responseText) => {
const doc = new DOMParser().parseFromString(responseText, 'text/html');
console.log(doc.querySelector("#qti-choiceinteraction-container > tbody > tr.checkedrow > td.answer > div > label > span > p")+"\n");
})
.catch((err) => {
// There was an error, handle it here
});
}
//console.log(finalString);
}
问题是,当我运行此命令时,需要花一点时间从另一个网页获得答复,但是循环继续执行而没有得到答复并打印出结果。我想等到元素被打印出来,然后再进行循环的下一次迭代。
答案 0 :(得分:0)
这里的问题是同步代码(即for循环)和异步代码(current
网络请求)的组合,这导致您注意到了不良行为。解决方案是阻止(阻止)循环的后续迭代,直到当前迭代中的异步网络调用完成为止。
有多种方法可以实现这一目标-一个基于Promise的解决方案是使用Promise.all()
评估多个Promise(即,对于每个循环迭代),以确保所有迭代都在锁定步骤中彼此执行。请参阅下面的代码修改后的副本,并附带详细说明如何完成此操作的注释:
fetch()
希望有帮助!
答案 1 :(得分:0)
您可以使用async并等待使其更简单。只需在函数中添加异步并使用await处理获取。
async function together(){
var finalString ="";
var x = document.getElementsByClassName("h-userinput");
for (var i = 0; i < x.length; i++) {
var text = x[i].innerText || x[i].textContent;
console.log(text+"\n");
var query = "#ctl00_ContentPlaceHolder_ResultsGrid_TB > tr:nth-child(bbcc) > td.total-score-column";
query = query.replace("bbcc",i+1);
var poop = ((document.querySelector(query)).onclick.toString());
text = poop.replace("javascript:location.href=\'","");
text = text.replace("function onclick(event) {","");
text=text.replace("}","");
text = text.replace("\';","");
text = "https://bartholomew.itslearning.com"+text;
var url = text;
try{
let res = await fetch(url)
let responseText = res.text()
const doc = new DOMParser().parseFromString(responseText, 'text/html');
console.log(doc.querySelector("#qti-choiceinteraction-container > tbody > tr.checkedrow > td.answer > div > label > span > p")+"\n");
}
catch{ console.log('Error')}
}
//console.log(finalString);
}