I've been doing a lot of reading online trying to figure out how to write asynchronous JavaScript code. One of the techniques that has come up a lot in my research is to use callbacks. While I understand the process of how to write and execute a callback function, I'm confused why callbacks seem to automagically make the JavaScript execution asynchronous. So, my question is: how does adding in callback functions to my JavaScript code make said code automagically async?
|
It doesn't. Just taking a callback or passing a callback doesn't mean it's asynchronous. For example, the
The
Hooking to any asynchronous event in Javascript always requires a callback but that doesn't mean calling functions or passing them around is always asynchronous. |
|||||||||||||||||||||
|
The secret of the "magic" is that the events that you are assigning the callbacks to are asynchronous. They're implemented "under the hood" to take care of whatever they're doing (such as retrieving something from a remote server) in the background, outside of the JS sandbox. And then once they're done with their work, they give the JS engine a message to call an event. When the JS engine is finished with whatever it's currently doing, it will call any events that are queued up (or wait for a new message) and then your callback is "magically" invoked asynchronously! (NOTE: This is a very high-level, conceptual overview of the topic that doesn't go into details, because different JS engines are going to implement things in different ways. But this is the general idea of how it works.) |
|||||
|