【问题标题】:How do I return callback of MySQL query and push to an array in Node.js?如何返回 MySQL 查询的回调并推送到 Node.js 中的数组?
【发布时间】:2017-03-31 02:11:52
【问题描述】:

我正在尝试使用 MYSQL 查询填充一个数组,该查询获取所有行并将行推送到 WordList。

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

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

【问题讨论】:

  • 你的方法getWord异步!所以第二个console.log(wordList); 在返回任何结果之前打印(在你第一次调用wordList.push(result); 之前)
  • 那么我怎样才能真正检索结果数据,以便我可以操纵它并做其他各种事情。我不需要打印它。

标签: javascript mysql node.js callback


【解决方案1】:

您的方法 getWord 是异步

所以第二个console.log(wordList); 在返回任何结果之前打印(在你第一次调用wordList.push(result); 之前)

此外,由于您在 getParrotMessage 函数中查询 db(这是异步的),因此您需要使用回调(或 Promise 或任何其他可以使用的东西)而不是 return 语句。

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']

});

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 2013-04-14
    • 2015-07-02
    • 2019-09-11
    • 2014-09-27
    • 2021-08-25
    • 2020-11-16
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多