Mil0R3
Mil0R3

Reputation: 3956

Callback not executing asynchronously in Node.js

A callBack function:

function queryDemo(param,callBack){
    function sleep(milliSeconds) {
        var startTime = new Date().getTime();
        while (new Date().getTime() < startTime + milliSeconds);
    } 
    sleep(10000);
    callBack(param);
}

Express code:

app.get('/demo', function(req, res){
    console.log(1);
    queryDemo(JSON.stringify(req.query),function(result){
        console.log(2);
    });
    console.log(3);
});

Then browse http://127.0.0.1/demo, the output in console is

1
//wait 10 seconds here
2
3

I think the right output should be:

1
3
// 10 seconds later
2

Upvotes: 0

Views: 449

Answers (2)

hexacyanide
hexacyanide

Reputation: 91599

The callback will execute synchronously unless you queue it to run on the next iteration of the event loop. This is what process.nextTick() is used for.

function queryDemo(param, callback) {
  function sleep(milliseconds) {
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + milliseconds);
  } 
  sleep(10000);
  process.nextTick(function() {
    callback(param);
  });
}

However, if you use this, you will still block the application and get this output:

1
// 10 second pause
3
2

To delay the execution of the function itself, then queue the calling of the function itself:

process.nextTick(function() {
  queryDemo(JSON.stringify(req.query), function(result) {
    console.log(2);
  });
});

Also do note that your sleep() function will still block the application, so you should be using setTimeout() instead.

Upvotes: 3

Jason
Jason

Reputation: 15931

I think you are killing the thread with that tight loop. Why are you trying to write you own sleep function instead of the built in timers setTimeout or setInterval?

Upvotes: 1

Related Questions