I’m getting this little trouble while looping, I always get the same “y” value (5) and it doesn’t decreases or increases. What I want is to repeat the ajax call X times [all] and pass the response and the current call number thru an anonymous function. I hope you can help me.
function _shds(long, count, func) {
for (var y = 0; y < count; y++) {
gapi.client.load('urlshortener', 'v1', function() {
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': long
}
});
var resp = request.execute(function(resp) {
func(resp.id, y);
});
});
}
}
var total = 3;
var base = "soem";
var lista = ["1", "2", "3", "4", "5"];
_shds("222", total, function(data, y) {
if (data != "undefined") {
newbase = base.replace("soem", data);
console.log(lista[y].uid + newbase + " pos:" + y);
}
});
UPDATE: Sorry, here’s an example of the code: http://jsfiddle.net/ZgXZB/
This is a trickier problem than it first appears, and a common JavaScript gotcha. What is going on is that when you say:
You are creating a closure on
yin the function callback that you pass toget. However, you only have created one closure and it has the final value ofywhich iscount. What you want to do is createcountdifferent closures, so you need to introduce a new scope:I believe that should do it. You need to declare a new function to create a new scope in JavaScript, and by passing
yas a parameter to that function you are creating a new closure for each value ofy.