2012-12-23 261 views
0

我在Node.js中處理異步事件。多個異步http獲取請求

我的應用程序正在執行第一個HTTP GET請求,然後根據響應正文中發現的一些信息循環一定次數。

在每次迭代時,它會調用一個函數,它發送其他HTTP GET請求並返回元素數組中推送的結果。

我的問題是,我想console.log()所有的http請求完成時的元素數組。這裏是我的代碼:

http.get('mysite.com', function(res) { 
    var body = ''; 
    res.on('data', function(chunk) { 
     body += chunk; 
    }); 
    res.on('end', function() { 
     var last = 5, 
      elements = []; 
     for(var i=0; i < last; i++) { 
      elements.push(myRequest(i)); 
     } 
     console.log(elements); 
     // Do some stuff with the elements array after it has been populated 
    }); 
}).on('error', function(error) { 
    console.log(error); 
}); 

var myRequest = function(i) { 
    http.get('mysite.com/page' + i, function(res) { 
     var body = ''; 
     res.on('data', function(chunk) { 
      body += chunk; 
     }); 
     res.on('end', function() { 
      // Do parsing here 
      return parsed; 
     }); 
    }).on('error', function(error) { 
     console.log(error); 
    }); 
}; 

我想過使用異步模塊,但我不確定如何在此用例中使用它。

在此先感謝!

+0

一個HTTP獲取是由定義的異步。不要真的看到你想做什麼。 – asgoth

+0

我只是想完成所有http請求的結果。 –

回答

2

我會使用異步庫,也許使用隊列。但是如果你想用手工完成,沒有在下面進行任何測試,也不確定它是否是最乾淨的方式,但它可能會給你一些想法。

傳遞迴調到您請求的功能:

var myRequest = function(i, cb){ 
    ... 
    res.on('end', function(){ 
     cb(parsed); 
    }); 
} 

及以上onEnd呼叫會看起來更象這樣:

var last = 5, elements = []; 

var rep = function(i){ 
    if(i < last){ 
    myRequest(i, function(result){ 
     elements.push(result);    
     rep(i+1); 
    }); 
    } else { 
    console.log(elements); 
    // Do some stuff with the elements array after it has been populated 
    } 
} 

res.on('end', function() { 
    rep(0); 
}); 

使用異步會出來很多更好看。儘管現在要運行...

+0

哼,它似乎沒有工作。該應用程序只是掛起,什麼都不做/不打印任何東西。 –

+0

從我所看到的情況來看,第一個http.get請求的「結束」事件從未被觸發。 –

+0

我修正了一些已經發布的範圍,現在就可以使用!非常感謝你。 –