node.js: while loop callback not working as expected

前端 未结 4 664
走了就别回头了
走了就别回头了 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: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.

提交回复
热议问题