简体   繁体   中英

Callback of an asynchronous function is never called

I have this function which waits for an asynchronous function to do its job and then returns.

function synchronous(){
    var notYet = true;

    setTimeout(function(){
        notYet = false;
    }, 1000);

    while(notYet)
        ;

    return "Done synchronously!";
}

console.log(synchronous());

Here the function synchronous stall using the while loop untill the callback of the asynchronous function (here setTimeout ) get executed. But, the callback is never called (checked using an alert inside the callback), therefore, notYet will remain true and the function loop will go forever. So, why doesn't the callback get called after 1000 ms?

NOTE: I don't care how to make an asynchronous function into a synchronous one. My question is why the callback not getting called?

The callback isn't getting called because the only thread that can call it is tied up doing your infinite loop.

In browsers, JavaScript runs on a single main UI thread (plus as many web workers as you want to create). That thread runs on a job queue: It picks up a job to do (for instance, processing a click), does the job, and then yields back to wait for the next job. You're blocking that one thread with the infinite loop. The timer schedules the callback in the job queue (probably, that's implementation-specific), but the thread never finishes the current job (the one that called your infinite loop) and so it never picks up that next job.

NodeJS also runs your code in a single thread and so does the same thing. (Not all environments do, but I'm not aware of any with setTimeout that don't schedule the timer callback on the same thread that requested it.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM