2014-02-24 140 views
1

我在for循環中做異步調用,我知道響應即將到來的異步,但我怎樣才能得到我的反應總是在同一順序。這裏是我的代碼:異步回調for循環響應不按順序

setInterval(function() { 
    callback = function (response) 
    { 
     var temp2 = ''; 
     var str = ""; 
     test = []; 
     console.log('STATUS: ' + response.statusCode); 
     response.setEncoding('utf8'); 
     response.on('data', function (chunk) 
     { 
      str += chunk; 
     }); 

     response.on('end', function() 
     { 
      console.log("end found"); 
      temp2 = JSON.parse(str); 
      for (var i in temp2['build']) 
      { 
       test.push(temp2['build'][i]['id']); 
       var req3 = http.request({ 
        host: host, // here only the domain name 
        auth: auth, 
        port: 8111, 
        path: '/httpAuth/app/rest/builds/id:' + test[i] + '/statistics/', // the rest of the url with parameters if needed 
        method: 'GET', // do GET 
        headers: { "Accept": "application/json" } 
       }, callback2); 
       req3.end(); 
      } 
     }); 
    } 

    var req4 = http.request(options4, callback); 
    req4.end(); 


    callback2 = function (response) { 

     //console.log('STATUS: ' + response.statusCode); 
     //console.log('HEADERS: ' + JSON.stringify(response.headers)); 
     response.setEncoding('utf8'); 
     var str2 = ""; 
     response.on('data', function (chunk) { 
      str2 += chunk; 
     }); 

     response.on('end', function() { 
      points.push(parseInt(JSON.parse(str2)["property"][2]["value"])); 

     }); 
     j++; 
     if (j == test.length) { 
      var sumTotal = 0; 
      var sumThree = 0; 
      var status = ''; 
      for (var i in points) { 
       sumTotal += points[i]; 
      } 
      var averageTotal = parseInt(Math.round(sumTotal/points.length)); 
      for (var i = 0; i < 3; i++) { 
       sumThree += points[i]; 
      } 
      var averageThree = parseInt(Math.round(sumThree/3)); 
      /*if(averageThree>averageTotal) 
      { 
       status='warning'; 
      } 
      else 
      { 
       status='ok'; 
      }*/ 
      console.log('average: ' + averageThree + ' average 100 ' + averageTotal + ' status ' + status); 
      //send_event('speed', {current: averageThree/*, status: status*/, last: averageTotal}); 
      j = 0; 
      points = []; 
     } 
    } 
}, 15 * 1000); 

所以我的問題是我怎麼能肯定我的反應「點的」始終以相同的順序。我試着發送變種我到回調函數,但不能讓它工作

編輯: 改變格式。 第一回調的輸出:

{ 
"count":100, 
"nextHref":"/httpAuth/app/rest/builds/?locator=buildType:bt2,count:100,status:SUCCESS,start:100", 
"build":[ 
    { 
    "id":17469, 
    "number":"5075", 
    "status":"SUCCESS", 
    "buildTypeId":"bt2", 
    "startDate":"20140224T183152+0100", 
    "href":"/httpAuth/app/rest/builds/id:17469", 
    "webUrl":"http://x.x.x.x:8111/viewLog.html?buildId=17469&buildTypeId=bt2" 
    }, 
    { 
    "id":17464, 
    "number":"5074", 
    "status":"SUCCESS", 
    "buildTypeId":"bt2", 
    "startDate":"20140224T165758+0100", 
    "href":"/httpAuth/app/rest/builds/id:17464", 
    "webUrl":"http://x.x.x.x:8111/viewLog.html?buildId=17464&buildTypeId=bt2" 
    }, 
    { 
    "id":17461, 
    "number":"5073", 
    "status":"SUCCESS", 
    "buildTypeId":"bt2", 
    "startDate":"20140224T161852+0100", 
    "href":"/httpAuth/app/rest/builds/id:17461", 
    "webUrl":"http://x.x.x.x:8111/viewLog.html?buildId=17461&buildTypeId=bt2" 
    }, 

此輸出包含100個項目。從這個輸出中我得到了id號,並用這個id數組發出了一個新的請求。這個新的回調給了我構建持續時間,但問題是因爲這是異步發生的,我得到的響應不是來自最新的構建,而是來自第一響應。所以我的問題是我怎樣才能以正確的順序得到這些生成速度數組

+0

您目前的和預期的輸出在這裏很有用。此外,您的代碼的格式將使它更易於閱讀。 **注意'for..in'代表一個對象的屬性,而不是一個數組迭代器(就像在C#或類似的代碼中一樣)。**我看到你使用了很多,並考慮['Array.prototype.forEach )'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)在迭代數組時(或者只是一個普通的'for-loop',而不是' for..in'循環) – clay

回答

1

不建議在for循環中使用匿名函數。

最好的方法(對我來說),就是使用異步庫。

簡單爲例來回答你的問題:

var objectList = [ 
    {"name":"Doe", "firstname":"John", "position":1}, 
    {"name":"Foo", "firstname":"Bar", "position":2}, 
    {"name":"Gates", "firstname":"Bill", "position":3}, 
    {"name":"Jobs", "firstname":"Steve", "position":4}, 
]; 
var arr = []; 

async.each(objectList, function(person, callback) { 
    arr.push(person); // async.each is asynchronous, so at the end, the order will be bad 
}, function(err) {   
    async.sortBy(arr, function(p, callback) { // Reorder 
     callback(err, p.position); 
    }, function(err, results) {    
     callback(null, results); // Send the result 
    }); 
}); 

這個例子將針對您的問題的工作。