我正在使用Node JS向数据库发出请求。碰巧我正在做一个SELECT语句,之后我需要它的结果来执行INSERT。
var index = 1;
async.whilst(
function() { return index < 10; },
function(callback) {
index++;
let line = csv_json[index][0].split(';');
let block = csv_json[index];
read_account(line);
callback(null, index);
},
function(err, n) {
if (err) throw err;
}
);
function read_account(csv, index) {
if (index == csv_json.length) return;
let line = csv_json[index][0].split(';');
let block = csv_json[index];
var account = line[0];
waterfall([
function(callback) {
connection.query('SELECT id FROM account WHERE account_number = ' + account,
function(error, results, fields) {
if (error)
throw error;
console.log(results);
callback(null, results);
});
},
function(results, callback) {
if (results == null || typeof results == undefined || results.length == 0) {
console.log("ENTREI");
connection.query('INSERT INTO account (account_number) VALUES (' + account + ')',
function(err, results, fields) {
callback(err, "1 account inserted!")
if (err)
throw err;
});
}
//else callback(null,"record already in db")
},
], function(err, success) {
if (err) throw err;
//console.log(success);
});
};
由于Node是异步的,当我调用read-account()时,我从INSERT得到的结果总是来自数据库的第一个状态。如何使这个进程同步?
谢谢
答案 0 :(得分:0)
您可以在Select函数的回调中编写第二个函数。
function read_account(csv, index) {
if (index == csv_json.length) return;
let line = csv_json[index][0].split(';');
let block = csv_json[index];
var account = line[0];
connection.query('SELECT id FROM account WHERE account_number = ' + account,
function(error, results, fields) {
if (error)
throw error;
console.log(results);
if (results == null || typeof results == undefined || results.length == 0) {
console.log("ENTREI");
connection.query('INSERT INTO account (account_number) VALUES (' + account + ')',
function(err, results, fields) {
callback(err, "1 account inserted!")
if (err)
throw err;
});
}
});
};
您可以考虑为select和insert编写两个不同的函数:
function select(callback){
connection.query('SELECT id FROM account WHERE account_number = ' + account, function(error, results, fields) {
if (error) {
return callback(error);
} else {
return callback(null, results, fields);
}
});
}
function insert(results, fileds, callback){
connection.query('INSERT INTO account (account_number) VALUES (' + account + ')',
function(err, results, fields) {
if (err){
return callback(err);
} else {
return callback(null, "1 account inserted!")
}
});
}
function read_account(csv, index, callback) {
if (index == csv_json.length) return;
let line = csv_json[index][0].split(';');
let block = csv_json[index];
var account = line[0];
select(function(null, results, fields){
if(err){
return callback(err);
} else {
insert(results, fileds, callback);
}
});
}