node.js: while loop callback not working as expected

前端 未结 4 676
走了就别回头了
走了就别回头了 2021-02-06 04:36

Knowing that while Node.js is working asynchronously, writing something like this:

function sleep() {
    var stop = new Date().getTime();
    while(new Date().g         


        
相关标签:
4条回答
  • 2021-02-06 04:58

    You are calling sleep right away, and the new sleep function blocks. It keeps iterating until the condition is met. You should use setTimeout() to avoid blocking:

    setTimeout(function () {
        console.log('done sleeping');
    }, 15000);
    
    0 讨论(0)
  • 2021-02-06 05:15

    Callbacks aren't the same thing as asynchronicity, they're just helpful when you want to get a... callback... from an asynchronous operation. In your case, the method still executes synchronously; Node doesn't just magically detect that there's a callback and long-running operation, and make it return ahead of time.

    The real solution is to use setTimeout instead of a busy loop on another thread.

    0 讨论(0)
  • 2021-02-06 05:18

    Javascript and node.js are single threaded, which means a simple while blocks; no requests/events can be processed until the while block is done. Callbacks don't magically solve this problem, they just help pass custom code to a function. Instead, iterate using process.nextTick, which will give you esentially the same results but leaves space for requests and events to be processed as well, ie, it doesn't block:

    function doSleep(callback) {
        var stop = new Date().getTime();
    
        process.nextTick(function() {
            if(new Date().getTime() < stop + 15000) {
                //Done, run callback
                if(typeof callback == "function") {
                    callback();
                }
            } else {
                //Not done, keep looping
                process.nextTick(arguments.callee);
            }
        });
    }
    
    doSleep(function() {
        console.log("done sleeping");
        console.log("DONE");
    });
    
    0 讨论(0)
  • 2021-02-06 05:19

    As already mentioned, asynchronous execution should be achieved by setTimeout() rather than while, because while will freeze in one "execution frame".

    Also it seems you have syntax error in your example.

    This one works fine: http://jsfiddle.net/6TP76/

    0 讨论(0)
提交回复
热议问题