This is an interesting question.
Asynchronous programming is a programming paradigm that is basically single-threaded, i.e. "after one thread of continuous execution."
You are referencing javascript, so let's discuss this language in a web browser environment. The web browser launches one javascript execution thread in each window, processes events (for example, onclick = "someFunction ()") and network connections (for example, xmlhttprequest calls).
<script> function performRequest() { xmlhttp.open("GET", "someurl", true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { alert(xmlhttp.responseText); } } xmlhttp.send(sometext); } </script> <span onclick="performRequest()">perform request</span>
(This is a non-working example, only to demonstrate concepts).
To do everything in asynchronous mode, the control thread has a so-called "main loop". The main loop looks something like this:
while (true) { event = nextEvent(all_event_sources); handler = findEventHandler(event); handler(event); }
It is important to note that this is not a βbusy cycleβ. It is like a sleeping thread awaiting activity. The activity can be entered by the user (Mouse movement, button click, Enter), or it can be network activity (response from the server).
So in the example above
- When the user clicks on the span, the ButtonClicked event will be generated, findEventHandler () will find the onclick event in the span tag, and then this handler will be called with the event.
- When an xmlhttp request is created, it is added to the list of event sources all_event_sources.
- After returning the function executeRequest (), mainloop waits for the next step nextEvent (), which is awaiting a response. At this point, nothing is blocked by further events.
- Data is returned from a remote server, nextEvent () returns a network event, the event handler is the onreadystatechange () method, this method is called and the alert () dialog is called.
It is worth noting that alert () is a blocking dialog box. Until this dialog is completed, further events cannot be processed. This is the eccentricity of the javascript model of web pages, we have an easily accessible method that blocks further execution in the context of this page.
Jerub Mar 05 '09 at 23:14 2009-03-05 23:14
source share