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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…