I have a loop making several ajax calls to an API. For each call there would be callback. The problem happen when there's an error and no data is returned, I am not able to know which call made that error.
How do I detect the call that caused this error inside the callback function? here's part of the code:
for (var i = 0; i < channels.length; i++) {
if ($.inArray(channels[i], livenow) > -1) {
continue;
}
this.chname = channels[i]; //this is the channel name
Twitch.api({
method: 'channels/' + this.chname
}, function(error, list) {
//insdie this callback
//chname may have been changed when we received the callback
console.log(this.chname + '===>');
now, I am not sure what value of chname was called in the API to make the error. when there's no errors, I depend on the data returned from the server to know the callback was a result of which call. when the server return an error, I am not able to know which call this callback is for.
as @boaz suggested, using closure would keep the environment for each call. So, the code would look like :
function mycall(chname) {
function twitchcall() {
Twitch.api({
method: 'channels/' + chname
}, function(error, list) {
//callback code would be able to access chname when the twitch call was made
});
};
return twitchcall;}
now to use the closure above, we write the following inside the loop
//now to use it inside the loop
calls[i] = mycall(xchname);
calls[i]();
for a full example http://codepen.io/TamerMarzouk/pen/VabQvP