AJAX - The Complete Reference

(avery) #1

248 Part II: Developing an Ajax Library^


As shown in the preceding code, AjaxTCR.comm.queue.requestQueueConcurrentR-
equests defines the number of requests to service at a time. In this case the number of
outstanding requests is compared to the number of requests to be sent. Since by default the
value of requestQueueConcurrentRequests is 1, the queue will send only a single item
at a time, pushing the rest to the queue array. Of course, it is easy enough to set the
concurrent request limit to whatever you want.

NNOTEOT E _requestQueue is simply a JavaScript Array type that has native push() and shift()
methods that can be used to create a queue data structure.

As requests are completed, the request queue will be checked. In each of the private
methods like _timeoutRequest(), _retryRequest(), and _handleResponse(), the
queue is consulted to see if there are any requests ready to be sent. As an example, in the
_retryRequest() method, note how after the function is done trying a request, it first goes
to the callback as normal and then checks the queue by calling _checkRequestQueue() to
see if there are more requests to send.

_retryRequest : function (request) {
/* up our retry count */
request.retryCount++;

/* make sure we aren't done retrying */
if (request.retryCount <= request.retries)
{
AjaxTCR.comm._makeRequest(request);
request.onRetry(request);
}
else /* stop trying and perform callback */
{
request.onTimeout(request);
AjaxTCR.comm.queue._checkRequestQueue(request);
}
}

The private _checkRequestQueue() method is quite simple. It looks to see if a queue
is being used and, if so, finds the next item to send.

_checkRequestQueue : function(response){
/* If Request Queue is being used, send next request */
if (response.inQueue && AjaxTCR.comm.queue._requestQueue.length > 0)
{
var nextRequest = AjaxTCR.comm.queue._requestQueue.shift();
AjaxTCR.comm.sendRequest(nextRequest.url, nextRequest.options);
}
}

With a simple request queue implemented, the timeout problem previously presented is
eliminated (http://ajaxref.com/ch6/requestqueue.html), as shown in Figure 6-9. In this
case, just the two latent requests timeout; the rest go through just fine.
Free download pdf