Asynchronous function means no blocking, and mostly, it keeps with a callback function. In c# and java, when calling function asynchronously, there must be more than one threads involved. Thus, threads are doing job parallelly, and the callback function will be called when the asynchronous method is finished.
Language like javascript is single thread. So how dose it implement the asynchronous function?
I read some articles and I know it take the event loop and setTimeout function to make a callback. But is it so-called asynchronous? Because I don't think it remove the blocking, because it is single thread. (I know that ajax is real asynchronous,because it use another thread which is supported by browser)
Do I misunderstand something?
@Joachim Isaksson: you and I both agree that asynchronous call is no blocking, but in javascript, asynchronous call using setTimeout function just delay the blocking, it never remove the blocking.
function f1(callback){
setTimeout(function () {
// f1's logic
callback();
}, 1000);
}
f1(f2);
As the codes, f1's logic will be delayed and when f1 is finished, it will callback the f2. It looks like asynchronous. But it just delay the blocking.
Javascript run synchronously (in one thread), but all I/O operations are asynchronous, that means that the calls are non-blocking, and when finished, the callback won't interrupt the running code, but will run synchronously once the current code is finished. So, it doesn't delay the blocking. Here is an example:
console.log("before async call");
setTimeout(function() { console.log("async stuff done"); }, 0);
console.log("after async call");
This will always display
before async call
after async call
async stuff done
But now, if you do:
console.log("before async call");
setTimeout(function() { console.log("async stuff done"); }, 0);
console.log("after async call");
while (true) {
// Do nothing
}
This will just display:
before async call
after async call
async stuff done is never displayed, because the while (true) lock the execution.