In a chrome extension I am writing I need to validate some objects I have stored in localStorage against my server . For this I created a for loop that simply sends the data for each localstorage element and that needs to do something with the response . The code is something like this:
for (var key in localStorage) {
if (! some condition )
continue;
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.response == 200) {
do something with 'key' from the for loop
}
}
};
var url = BASE_PATH ;
httpRequest.open("POST", url);
httpRequest.send(some data);
}
However while debugging it seems that in the ajax response , the 'key' from the for loop isn't the key I need : I was expecting to get the same key from the for loop that matches each ajax call , what I got was the same key for all ajax calls . Am I doing something wrong or expecting something that isn't possible ? I thought that since the ajax is inside a closure function , the values are kept in memory or something of the sort .