0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Point to add: Even the OP is using callback, the calling is not asynchronous.
1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.