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

这篇博客探讨了在JavaScript和Node.js中进行MySQL查询时遇到的问题,即如何正确地将查询结果填充到数组中。作者指出,由于getWord函数的异步性质,导致在getParrotMessage方法外部无法获取到正确的数据。解决方案是使用回调函数处理异步操作,确保在数据获取后填充wordList。通过调整代码结构,实现了异步查询的正确处理和数据的正确返回。
摘要由CSDN通过智能技术生成

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

解决方案

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

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值