Or Smith
Or Smith

Reputation: 3596

Why does Node.js not execute the callback function?

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?

Upvotes: 0

Views: 821

Answers (1)

mthierer
mthierer

Reputation: 604

Your code misses the part where PostCode() is called, but it's probably something like a for-loop. As you already found out, that only fills the event queue which only gets executed when no other code is running.

You might try something like this:

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();

Then you set an listener for the "end" event on the ClientRequset returned from http.request() and call postNextStream() from there.

This makes all the requests sequentially. If you want some kind of parallelism, you have to implement a more sophisticated queue management in postNextStream().

Upvotes: 1

Related Questions