AJAX - The Complete Reference

(avery) #1

256 Part II: Developing an Ajax Library^


The general solution to race conditions is to be aware that they might happen and write
code to avoid them. In this case it is fairly simple: Just be sure to lock the session before writing
to it. As demonstrated in other examples, if order really does matter, you must be more careful
in sending the requests. To ensure that the requests arrive at the server in a certain manner, it
may be necessary to use a request queue and only send one request at a time.

Ensuring Communication Robustness


One thing is consistent in the world and that is change. On the Internet, conditions change
from moment to moment. Just because the server is up for a moment doesn’t mean it always
will be. Just because you encountered a few retries doesn’t mean the connection is mostly
bad. You need to keep track of the situation over time for a true picture of the robustness of
the network and server connection. In this section, a few approaches to Ajax connection
monitoring are presented. If you employ connection monitoring you shouldn’t be surprised
that it tells you that things really do go quite wrong on the Internet.

Server Availability


Given that HTTP is a connectionless protocol, the only way to know if the connection is still
usable is simply to use it. To address this unknown, you might employ a heartbeat pattern and
ping the server using a simple XHR request every so often. For example, the demo at http://
ajaxref.com/ch6/ping.html makes a small request to the server every three seconds to see if

FIGURE 6-15 Race conditions can but shouldn’t happen
Free download pdf