我的所作所为:
预期结果:经过4个步骤后,无论如何都会产生结果
结果:select中没有行,但该行存在(请参阅phpMyAdmin)
mysqlPool.getConnection(function(err, connection) {
connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
if (result.length == 0) {
// this works, I verified through phpMyAdmin:
connection.query('INSERT INTO x SET ?', { key: data.key });
}
});
connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
if (result.length != 0) {
// Expecting to be here, but result[0] is undefined?!
} else {
// I END UP HERE? wtf
}
});
connection.release();
});
node-mysql是否需要commit;
或类似的东西?
我做错了什么?
答案 0 :(得分:2)
我认为这是由于Node的异步性质,你需要在插入后调用回调中的第二个选择。类似于以下内容
mysqlPool.getConnection(function(err, connection) {
connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
if (result.length == 0) {
// this works, I verified through phpMyAdmin:
connection.query('INSERT INTO x SET ?', { key: data.key }, function(err, result){
secondSelect();
});
}
else
secondSelect();
});
});