用于循环的can'不要等待

A for cycle can't wait

本文关键字:等待 循环 can 用于      更新时间:2023-09-26

如何强制循环在运行之前等待每个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)
}
})

您可以在XHR请求上附加一个回调函数,检查是否满足for循环的停止条件,然后停止,或者再次进行请求,而不是使用for循环。

您可以使用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
         }
    };