Node.js nodejseventloop执行顺序
当连续发送多个请求时,看起来Node.js nodejseventloop执行顺序,node.js,events,Node.js,Events,当连续发送多个请求时,看起来 在发送所有请求时执行回调 请求似乎被添加到队列中,但在循环完成之前实际上并未得到执行 示例 var http = require('http'); var i=0; var postData = []; while (i++ < 12) { var largeObject = [ 'this' + i, 'that' + i, 'then' + i ]; postData.pus
- 在发送所有请求时执行回调
- 请求似乎被添加到队列中,但在循环完成之前实际上并未得到执行
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 = [];
}
}
在执行下一个请求之前,是否有任何方法可以完成一个请求
我真的不在乎顺序,它更多的是关于内存-我想摆脱我张贴的大对象
e、 g
那绝对没问题。
有什么建议吗?当然,只需使用一些控制流模块,如async或bluebird 由于您不关心订单,我建议您使用或。
bluebird#map
有一个并发参数,当您需要对循环及其数量进行更多的控制时,这个参数会很好(async#parallelLimit)
如果这看起来不简单,请评论,我将添加一个示例。谢谢您的回答。也许这个问题不够清楚。在我的实际代码中,我正在每个循环周期中准备一个大对象,我希望尽快提交并从内存中清除它。我已经更新了上面的示例,以更好地反映我正在做的事情。例如,我看不出
async.parallel
对我有什么帮助。举个例子就好了。你说的“提交”对象是什么意思?例如,Async.parallel将允许您在每个请求完成时调用函数,然后在完成所有操作后进行最后一次回调。在我看来,你可以用一个简单的方法来实现你所需要的。
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