如何返回MySQL查询的callback,并推送到Node.js中的数组?

我想填充一个数组使用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是asynchronous的

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

另外,由于您在getParrotMessage函数中查询db(这是asynchronous的),您需要使用callback(或Promise或其他可以使用的)而不是返回语句。

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