如何强制循环等待每个XHR在运行之前完成?我知道一种评论方式,但它会杀死百分比计数器的实时性。
var data = new Array, per = 0;
WinJS.xhr({url : "http://index.hu/tech/rss"}).done(function(req){
$($.parseXML(req.response)).find("item title:lt(5)").each(function() {
data.push({
h : this.textContent
})
}).next().each(function(ind) {
WinJS.xhr({
url : this.textContent
}).done(function(req) {
per += 100 / 30;
$("#per").text(Math.ceil(per) + " %");
data[ind].p = req.response.match(/<p>(.+?)<\/p>/)[1]
})
/*var req = new XMLHttpRequest;
req.open("get", this.textContent, false);
req.onreadystatechange = function()
{
if(this.readyState == 4)
{
per += 100/30;
$("#per").text(Math.ceil(per) + " %");
data[ind].p = this.response.match(/<p>(.+?)<\/p>/)[1]
}
}
req.send()*/
})
for(var ind in data)
{
//console.log(data[ind].p)
}
})
答案 0 :(得分:1)
您可以在XHR请求上附加一个回调函数来检查是否满足for循环的停止条件,然后停止,或者再次生成请求,而不是使用for循环。
答案 1 :(得分:0)
您可以等待setTimeout
。请参见下面的setTimeOut(wheAllDone, 100);
行:
var items = $($.parseXML(req.response)).find("item title:lt(5)").each(function()
{
data.push(
{
h : this.textContent
})
}).next();
var itemsCount = items.length;
var doneSoFarCount = 0;
items.each(function(ind)
{
WinJS.xhr(
{
url : this.textContent
}).done(function(req)
{
per += 100 / 30;
$("#per").text(Math.ceil(per) + " %");
data[ind].p = req.response.match(/<p>(.+?)<\/p>/)[1]
doneSoFarCount ++;
})
});
var wheAllDone = null;
wheAllDone = function() {
if(doneSoFarCount >= itemsCount)
{
for(var ind in data)
{
//console.log(data[ind].p)
}
} else {
setTimeOut(wheAllDone, 100); // <<<<< Wait a bit for all to complete
}
};