How Do I Return Callback Of Mysql Query And Push To An Array In Node.js?
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
Solution 1:
Your method getWord is asynchronous!
So the second console.log(wordList);
is printed before any results are returned (before you even call wordList.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.
functiongetParrotMessage(callback) {
getWord('result', function (err, result) {
if(err || !result.length) returncallback('error or no results');
// since result is array of objects [{word: 'someword'},{word: 'someword2'}] let's remap it
result = result.map(obj => obj.word);
// result should now look like ['someword','someword2']// return itcallback(null, result);
});
}
functiongetWord(word, callback) {
con.query('SELECT * FROM word_table', function(err, rows) {
if(err) returncallback(err);
callback(null, rows);
});
};
now use it like this
getParrotMessage(function(err, words){
// words => ['someword','someword2']
});
Post a Comment for "How Do I Return Callback Of Mysql Query And Push To An Array In Node.js?"