我试图在表格中插入用户匹配,但我不想重复。 因此,我正在运行COUNT个查询,但当我尝试插入新记录时,我得到未定义,因此我无法插入记录。
我已经阅读了有关使用回调的内容,但对于目前正在努力的NodeJS来说还是一个新手。
if(user_matches.length !== 0){
var connection = mysql.createConnection({
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'test'
});
connection.connect();
//connection.query('TRUNCATE matches');
// I was originally truncating the table, but this just doesn't cut it
for (var x = 0; x < user_matches.length; x++){
var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ user_matches[x]['user_1']['id'] ]);
countQuery.on('result', function(){
// Here I get the UNDEFINED error, can't insert
connection.query('INSERT INTO matches SET ?', {
'user_id_1': user_matches[x]['user_1']['id'],
'user_id_2': user_matches[x]['user_2']['id']
});
});
}
connection.end();
}
答案 0 :(得分:1)
安装async
npm install async --save
然后试试这个:
if(user_matches.length !== 0){
var connection = mysql.createConnection({
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'test'
});
connection.connect();
async.each(user_matches, function(x, callback){
var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ x['user_1']['id'] ]);
countQuery.on('result', function(){
var insertQuery = connection.query('INSERT INTO matches SET ?', {
'user_id_1': x['user_1']['id'],
'user_id_2': x['user_2']['id']
});
insertQuery.on('result', callback);
});
}, function(err){
console.log('done');
});
}