I'm trying to iterate through an array of RSS feeds as below:
var rssFeeds = [ ['http://www.huffingtonpost.com/tag/womens-rights/feed/', "Huffington Post"], ['http://abcnews.go.com/topics/urss?pageid=681900', "ABC News"], ['http://www.globalissues.org/news/topic/166/feed', "Global Issues"], ['http://topics.nytimes.com/top/reference/timestopics/subjects/f/feminist_movement/index.html?rss=1', "The New York Times"] ];
This array contains both the location of the feed and a string with the name of the feed. I iterate through the array with a for loop as below, the one with i as an iterator.
Once I receive the results, I iterate through the results in the callback function with the for loop j. I append each fetched result to another array entryArray, and after appending each result, I add a new attribute 'source' to that fetched result using the name for the RSS feed.
function loadEntries()
{
var feedr = new Array();
for( var i = 0; i < rssFeeds.length; i++ )
{
feedr[i] = new google.feeds.Feed( rssFeeds[i][0] );
feedr[i].setNumEntries(loadAmount);
feedr[i].load(function(result) {
if (!result.error) {
console.log(i);
for (var j = 0; j < result.feed.entries.length; j++) {
entryArray[entryArray.length] = result.feed.entries[j];
entryArray[entryArray.length - 1]['source'] = rssFeeds[i][1];
}
}
});
}
}
However, and this is where the problem arises, the iterator I use (i) to indicate the name to append is always equal to rssFeeds.length, because the callback functions for all four load commands occur after the initial for loop has already finished iterating. The console.log(i); you see always returns 4.
This worked when I copied and pasted the code for each item individually, but I'd rather not copy and paste because the RSSFeeds array will probably be much longer in the future. Is there any way I can accomplish this with a loop?
So first of all, I'd like to thank nd_macias for providing me with the links that helped me find this solution. Basically, I wrapped the load function in a function, and then called that function with the for loop as below:
function loadEntries()
{
var feedr = new Array();
for( var i = 0; i < rssFeeds.length; i++ )
{
feedr[i] = new google.feeds.Feed( rssFeeds[i][0] );
feedr[i].setNumEntries(loadAmount);
var f = function(n) {
feedr[n].load(function(result) {
if (!result.error) {
for (var j = 0; j < result.feed.entries.length; j++) {
entryArray[entryArray.length] = result.feed.entries[j];
entryArray[entryArray.length - 1]['source'] = rssFeeds[n][1];
}
}
});
}
f(i);
}
}