I tried to iterate over an array using a for-loop. In the loop there is a ajax call which is asynchronous. I need it to use the current value of the for loop iteration and not the changed value when the ajax call is finally retrieved. I searched for a solution and stumbled upon closure with a function. Oddly, it doesn't seem to work in this case. Anyone who can help? Thanks!
Edit:
The last key value of the iteration is used for the titles of every feed. So he fetches the correct feed (feeds[key]) but in the success part, he just pushes last_key + title for every feed. I don't get any errors, the ajax call works correctly.
for (var key in feeds) {
(function(k) {
console.log('function: ' + k); // gives the correct keys, e.g. first time 'Reddit', second time 'Tweakers'
$.feedToJson({
feed: feeds[k],
success: function(data) {
console.log('succes: ' + k); // always gives the last key, e.g. always 'Tweakers'
for (var i in data.item) {
var item = data.item[i];
if (typeof item.title == 'object') {
news.push(k + ': ' + item.title[0]);
} else {
news.push(k + ': ' + item.title);
}
}
}
});
})(key);
}
var feeds = {
Reddit: 'https://www.reddit.com/r/leagueoflegends/.rss?sort=new',
Tweakers:'http://www.tweakers.com/feeds/nieuws.xml'
}
(function fetchNews() {
news = [];
for (var key in feeds) {
(function (k) {
console.log('function: ' + k); // gives the correct keys, e.g. first time 'Reddit', second time 'Tweakers'
$.feedToJson({
feed: feeds[k],
success: function(data){
console.log('succes: ' + k); // always gives the last key, e.g. always 'Tweakers'
for (var i in data.item) {
var item = data.item[i];
if (typeof item.title == 'object') {
news.push(k + ': ' + item.title[0]);
} else {
news.push(k + ': ' + item.title);
}
}
}
});
})(key);
}
setTimeout(function() {
fetchNews();
}, 60000);
})();
(function($) {
$.extend({
feedToJson: function(options, callback) {
if ($.isFunction(options)) {
callback = options;
options = null;
}
options = $.extend($.feedToJson.defaults,options);
var url = options.yqlURL + options.yqlQS + "'" + encodeURIComponent(options.feed) + "'" + "&_nocache=" + options.cacheBuster;
return $.getJSON(url, function(data){
//console.log(data.query.results);
data = data.query.results;
$.isFunction(callback) && callback(data); //allows the callback function to be the only option
$.isFunction(options.success) && options.success(data);
});
}
});
})(jQuery);