I'm trying to populate an array using a MYSQL query on a table that takes all rows and pushes the rows to WordList.
I can print each line within the method fine, but when I go out of the scope of that method it doesn't push anything to Wordlist.
function getParrotMessage() {
wordList = [];
console.log(wordList);
// Implementation
getWord('result', function (err, result) {
console.log(result); // works, prints the row data in MySQL table
wordList.push(result); // doesn't work
});
console.log(wordList);
return parrot_message;
}
// Method
function getWord(word, callback) {
var query = con.query('SELECT * FROM word_table');
query.on('result', function (row) {
callback(null, row.word);
});
};
wordlist: []
wordlist shows up as an empty array.
Any help would be greatly appreciated, just beginning with javascript and node.js
Your method getWord is asynchronous!
So the second
console.log(wordList);
is printed before any results are returned (before you even callwordList.push(result);
for the first time)Also since you query db(which is asynchronous) in getParrotMessage function you need to use callback (or Promise or whatever else there is that can be used) instead of return statement.
now use it like this