如何返回MySQL查询的回调并推送到Node.js中的数组? [英] How do I return callback of MySQL query and push to an array in Node.js?

查看:144
本文介绍了如何返回MySQL查询的回调并推送到Node.js中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MYSQL查询在填充所有行并将行推送到WordList的表上填充数组.

I'm trying to populate an array using a MYSQL query on a table that takes all rows and pushes the rows to WordList.

我可以很好地打印方法中的每一行,但是当我超出该方法的范围时,它不会将任何内容推送到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.

从javascript和node.js开始,任何帮助将不胜感激

Any help would be greatly appreciated, just beginning with javascript and node.js

推荐答案

您的方法getWord是异步

Your method getWord is asynchronous!

因此,在返回任何结果之前(甚至在您第一次调用wordList.push(result);之前),将打印第二个console.log(wordList);

So the second console.log(wordList); is printed before any results are returned (before you even call wordList.push(result); for the first time)

此外,由于您在 getParrotMessage 函数中查询db(异步),因此需要使用回调(或Promise或可以使用的其他方法)代替return语句.

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);
    });
};

现在像这样使用它

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

});

这篇关于如何返回MySQL查询的回调并推送到Node.js中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆