I have the following code with http module:
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();
}
I execute the postCode function 1000~ times in order to backup my filesystem.
The probelm is that the callback isn't executed, I see a sequence output of:
A
B
C
A
B
C
and so on.. without D.
Just when all the postCode were executed, the callback is starting to run.
How I exceute the callback parallel? So that also D will be printed?
EDIT:
this is the new question, hope it clear. I still don't understand how to fix this issue:
The problem is that I have a loop which call to function A.
In this function, there is a codeblock with execute a function with callback, let say that the callback is B.
Now, B call to other function C.
Meaning:
`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);
}
I see that C() callback is waiting until all A loop is finish, and just then execute.
In this case, that what I would see:
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
How can I fix it, so C would be printed after main, a, and b?
http.request(post_options, function(res) {...}will be executed, so each upload shouldn't wait to the other. but this doesn't happen:http.requestdoesn't executed (The server doesn't get the request), and for that the callback doesn't executed.