Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which thread is javascript callback function execute?

Tags:

javascript

Recently I read some aync I/O about javascript but I feel more confused about where is javascript execute its aync's callback? The main thread or other? Are there something difference with node and browser ?

like image 239
TommY Avatar asked Jan 28 '23 00:01

TommY


1 Answers

An async call handler is executed on the main thread when the response comes back.

If you execute it from a webworker, the async call handler will be handled in the webworker thread.

It roughly follows this setup from top to bottom.

parent thread
   |    
 async start 
   |
   - - - - - - > IO thread
   |                 |
 other stuff      make call
   |                 | 
 more stuff       get response
   |                 |
   | <--queue handling
   V
 handle async 
 response 

Technically there will be a difference between how node handles the io thread and a browser does, but for all intents and purposes you will experience the same results.

Look at the example below to see a "live demo" of how the async task gets pushed away to another thread, the main thread continues to do it's thing. Then the response comes, is enqueued into the main thread, then the main thread continues to do its thing when the handler is done.

var request = new XMLHttpRequest();

request.open('GET', 'https://api.jikan.moe/meta/requests/anime/today');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};
var start = 0;
request.send();
for(var c=0;c<1000;c++) {
  +function(c) { 
     start += 1;
  
     window.setTimeout(function() {
       console.log(start, c);
     },c); 
   }(c)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hit f12 and scroll through the log output
like image 77
Tschallacka Avatar answered Feb 12 '23 00:02

Tschallacka