How do I return callback of MySQL query and push t

2019-07-13 17:23发布

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

1条回答
Viruses.
2楼-- · 2019-07-13 18:12

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.

function getParrotMessage(callback) {

    getWord('result', function (err, result) {

        if(err || !result.length) return callback('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 it
        callback(null, result);

    });
}

function getWord(word, callback) {
    con.query('SELECT * FROM word_table', function(err, rows) {
        if(err) return callback(err);
        callback(null, rows);
    });
};

now use it like this

getParrotMessage(function(err, words){
    // words => ['someword','someword2']

});
查看更多
登录 后发表回答