Search code examples
javascriptajaxxmlhttprequestrace-condition

Race Condition because of multiple AJAX requests


my problem is the following. I wrote a class AJAXEngine, which creates in the constructor a new XMLHttpRequest object. The class contains a method called responseAnalyser, which is called when the "onreadystatechange" of the XMLHttpRequest object has changed. So now I created lets say 4 instances of AJAXEngine => 4 XMLHttpRequest objects.

Now I have another class DataRequester, which has an array-attribute dataReq, which holds the instances of AJAXEngine. There is only one instance of DataReqeuster in the whole program! DataRequester has a function called callWhenFinished. The function is called, by the function responseAnalyser of AJAXEngine and decrements a variable of the DataRequester instance.

But, I think there happen race conditions. How could I prefent them in JavaScript?

function AJAXEngine
{
 this.httpReqObj = //create new XMLHttpRequest Object
 this.obj;
 this.func;
}
AJAXEngine.prototype.responseAnalyser = function()
{
 if(this.httpReqObj.readState == 4)
 {
  this.func.call(this.obj);
 }
}
AJAXEngine.prototype.fireReq = function(o, f)
{
 this.obj = o;
 this.func = f;
 // fire ajax req
}

function DataRequester()
{
 this.dataReq = new Array();
 this.test = 4;

 for(var i = 0; i < 4; i ++)
 {
  this.dataReq[i] = new AJAXEngine();
 }
}
DataRequester.prototype.callWhenFinished = function()
{
 this.test --;
}

Solution

  • Not sure if this would help, but it looks like you're trying to create a managed connection pool. I did one a few years ago that still works fine here:

    DP_RequestPool Library

    The pool ensures that requests are made in the order you've provided them (although, of course, they may be returned in any order based on performance) using as many simultaneous requests as you define (subject to system limitations). You can instantiate multiple pools for different purposes.

    If nothing else this might give you some ideas.