2012-03-24 9 views
0

サイクルが実行される前にすべてのXHRが完了するのを待たせるにはどうしたらいいですか?私はコメントにある方法を知っていますが、パーセンテージカウンターのリアルタイムを殺します。サイクルのためのAは待つことができません

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

XHRは非同期で使用されるため、目的を破棄します。 –

答えて

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 
     } 
    }; 
1

の代わりにそのためのforループを使用して、あなたは他のforループの停止条件が満たされているかどうかを確認した後、停止し、またはXHR要求にコールバック関数を付けることができ請求をもう一度行います。

関連する問題