node.js: while loop callback not working as expected

前端 未结 4 682
走了就别回头了
走了就别回头了 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 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");
    });
    

提交回复
热议问题