1
當連續發送多個請求,這似乎是在所有的請求被髮送執行的NodeJS事件循環執行順序
- 回調。
- 請求似乎被添加到隊列中,但在循環完成之前並未真正執行。
例
var http = require('http');
var i=0;
var postData = [];
while (i++ < 12) {
var largeObject = [
'this' + i,
'that' + i,
'then' + i
];
postData.push(largeObject);
if (postData.length >= 2) {
console.log('request');
var options = {
hostname: 'httpbin.org',
port: 80,
path: '/post',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
var req = http.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(chunk) {
console.log(chunk.toString());
});
res.on('end', function() {
console.log('finished reading response');
});
});
req.end(JSON.stringify(postData), function() {
console.log('request stream finished');
});
postData = [];
}
}
這裏的輸出看起來像
request
request
request
request
request
request
request stream finished
request stream finished
request stream finished
request stream finished
request stream finished
request stream finished
200
{
"args": {},
"data": "[[\"this7\",\"that7\",\"then7\"],[\"this8\",\"that8\",\"then8\"]]",
"files": {},
"form": {},
"headers": {
"Content-Length": "53",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": [
[
"this7",
"that7",
"then7"
],
[
"this8",
"that8",
"then8"
]
],
"origin": "xxxxx",
"url": "http://httpbin.org/post"
}
finished reading response
200
{
"args": {},
"data": "[[\"this1\",\"that1\",\"then1\"],[\"this2\",\"that2\",\"then2\"]]",
"files": {},
"form": {},
"headers": {
"Content-Length": "53",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": [
[
"this1",
"that1",
"then1"
],
[
"this2",
"that2",
"then2"
]
],
"origin": "xxxx",
"url": "http://httpbin.org/post"
}
...
有什麼辦法來完成下一個前一個請求得到執行?
我真的不關心順序,它更多的內存 - 我想擺脫大型物體的我張貼
例如
request1
response1
request2
response2
request3
response3
request4
request5
response5
response4
將是絕對好的。 有什麼建議嗎?
謝謝你的回答。 也許這個問題還不夠清楚。 在我的真實代碼中,我正在爲每個循環週期準備一個大對象,我希望儘快提交併從內存中清除它。 我已經更新上面的例子,以更好地反映我在做什麼。 我不明白'async.parallel'會如何幫助我。 一個例子會很棒。 –
「提交」對象是什麼意思?例如,Async.parallel將允許您在每個請求完成時調用一個函數,然後在完成所有操作後再進行最後一次回調。國際海事組織,你可以用一個簡單的[EventEmitter](https://nodejs.org/api/events.html)來實現你所需要的。 – soyuka