filipedeschamps / rss-feed-emitter

Super RSS News Feed aggregator written in Node.js and ES6

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

for loop index issue.

icq4ever opened this issue · comments

why index in for loop is out of array index ??
could someone explain why ?

var rssFeeds = [];
var rssNames = [];
var rssUrl = [];

var con = mysql.createPool({
	connectionLimit:10,
	host: "_DB_HOST_",
	user : "_DB_USER_",
	password: "_DB_PASSWD",
	database : "_DB_NAME",
	multipleStatements: true
});

var sqlQuery = 'SELECT * FROM tblSources WHERE projectId = 1 AND isActive = 1 AND projectId = 1';

con.query(sqlQuery, function(errK, rowsK, fieldsK, callback){
	if(errK)	console.log(errK);
	for(var i=0; i<rowsK.length; i++){
		rssFeeds.push(new RssFeedEmitter());
		rssNames.push(rowsK[i].sourceName);
		rssUrl.push(rowsK[i].sourceRssUrl);
		console.log(rowsK[i].sourceName + " : added");	
	}

	for(var index=0; index<rssFeeds.length; index++){
		console.log(index);      <--- index = 0, 1, 2, 3, 4
		rssFeeds[index].add({refresh : 60000, url : rssUrl[index]});
		
		rssFeeds[index].on('new-item', function(item)	{ 
			console.log(index);        // index = 5??????? WHY?
                        console.log(rssUrl[index])    // so this is undefined
		});
	}
});

or is there any solution, that can pass 'value' to callbackfunction?

i want to pass rssName(string) to inside of
function(item){} callback function, can print with item.pusDate, item.Title... etc.

commented

well, you're making a ton of feed emitters like that, which is... really really bad.

commented
const rssFeeder = new RssFeedEmitter(); // don't make a bunch of these
const rssNames = [];
const rssUrl = [];

const con = mysql.createPool({
  connectionLimit:10,
  host: "_DB_HOST_",
  user : "_DB_USER_",
  password: "_DB_PASSWD",
  database : "_DB_NAME",
  multipleStatements: true
});

const sqlQuery = 'SELECT * FROM tblSources WHERE projectId = 1 AND isActive = 1 AND projectId = 1';

con.query(sqlQuery, function(error, rows, fields, callback) {
  if(error)  console.log(error);
  rows.forEach(row => {
    rssFeeder.add({ refresh: 60000, url: row.sourceRssUrl }); // I think your issue is how you're reading this below
    rssFeeder.on('new-item', (item) => {
      if (item.meta.link === row.sourceRssUrl) {
        callback(item);
      }
    })
  });
});

I simplified your logic a bit so you don't have to mess around with indices. I dunno if you'll check this tho...

@icq4ever

@TobiTenno thanks for comment. i'll check that . I'll close this issue.