我在http模块中有以下代码:
function PostCode(stream) {
// Build the post string from an object
console.log("Start upload: " + stream);
console.log("A");
var post_data = JSON.stringify({
'stream' : stream,
});
console.log("B");
// An object of options to indicate where to post to
var post_options = {
'host': 'myserver',
'port': '5000',
'path': '/upload',
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
}
};
// Set up the request
console.log("C");
var post_req = http.request(post_options, function(res) {
console.log("D");
res.setEncoding('utf8');
console.log(post_options);
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data,'utf8');
post_req.end();
}
我执行postCode函数1000次以备份文件系统。
该探查是未执行回调,我看到了以下输出的序列:
A
B
C
A
B
C
等等..没有D
。
就在所有postCode都已执行时,回调才开始运行。
我如何执行并行回调?这样D也将被打印出来吗?
编辑:
这是新问题,希望它清楚。我仍然不明白如何解决此问题:
问题是我有一个调用function的循环A
。
在此函数中,有一个代码块,其中包含一个执行带有回调的函数,可以说该回调为B
。
现在,B
调用其他函数C
。
意义:
`function main(){
for (int i = 0; i<5; i++){
console.log("main" + i);
A();
}
}
function A(){
// do some stuff
var u = http.request(o, function (res){
console.log("A" + i);
B();
})
}
function B(){
//do some stuff
var u = http.request(o, function (res){
console.log("B" + i);
C();
})
}
function C(){
console.log("C" + i);
}
我看到C()
回调正在等待所有A
循环完成,然后才执行。在这种情况下,我会看到:
main 0
A 0
B 0
main 1
A 1
B 1
main 2
A 2
B 2
main 3
A 3
B 3
main 4
A 4
B 4
C 0
C 1
C 2
C 3
C 4
我该如何解决它,所以C
会在maina
和之后打印b
?
您的代码缺少PostCode()
被调用的部分,但可能类似于for循环。正如您已经发现的那样,这仅填充事件队列,该事件队列仅在没有其他代码正在运行时才执行。
您可以尝试如下操作:
function postNextStream() {
if (streams.length > 0)
PostCode(streams.shift());
}
var streams = [];
for (*however you find the stuff you'd like to post*)
streams.push(stream);
postNextStream();
然后,在从那里返回http.request()
并postNextStream()
从那里调用的ClientRequset上为“结束”事件设置一个侦听器。
这将使所有请求依次执行。如果您需要某种并行性,则必须在中实现更复杂的队列管理postNextStream()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句