I have 2 different XMLHttpRequest objects making asynchronous requests to the same web service. The web service sends back a cookie in the HTTP response headers, that I can read with the chrome.cookies.read extension (the request is cross-domain).
Each xhr reads the same cookie by name, but the value of the cookie after each response will be different, as it is a unique token for each requester.
So I want to store each cookie value per request, just after receiving the HTTP response, for later use.
So here’s what my code is currently doing:
var my_cookie_value = [] ;
function begin()
{
for (var i = 0 ; i < 2 ; i ++)
{
sendRequest(some_url, i);
}
}
function sendRequest(some_url, thread)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
readCookie(thread) ;
}
}
xmlhttp.open("GET", some_url, true);
xmlhttp.send();
}
function readCookie(thread)
{
chrome.cookies.get(
{
"url" : some_domain,
"name" : "mycookie"
},
function(cookie)
{
if (cookie != null)
{
my_cookie_value[thread] = cookie.value ;
}
}
);
}
However because chrome.cookies.read uses a callback function with no guaranteed time to fire, I am finding the cookie values get mixed up (or repeated) for each thread, even though they were returned from the server as distinct values.
I think what can happen is:
thread 0 sends request
thread 1 sends request
thread 0 receives response
thread 0 requests cookie value callback
Arrgghh!!…worst case scenario coming up…
thread 1 receives response
thread 1 requests cookie value callback
thread 0 cookie callback fires and cookie value (FOR THREAD 1) is copied into my_cookie_value[0]
thread 1 cookie callback fires and cookie value (FOR THREAD 1) is copied into my_cookie_value[1]
This is obviously not what I wanted. my_cookie_value[0] and [1] both contain the token for thread 1.
So finally to the question: Is there another solution for this? I cannot rewrite the server code, I can only access the client.
I am wondering why oh why is reading a cookie done by a callback function??
Set up var that tracks if you currently have a request active. Something like
var currentRequest = falseand set it to true before starting a request and set it to false after a request is complete. Before starting a request check if there is an active request and if there is either delay or create a queue of pending requests.