我正在尝试获取一些结果并根据这些结果进行进一步处理,但我无法继续按顺序工作,
var sql = query1;
con.query(sql, function (err, results) {
if (err) throw err;
// ids => 5,2,3,4
for (i = 0; i < results.length; i++) {
target_user = results[i].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
})
})
}
})
上面的代码是异步运行的,我期望的是像这样的循环中的输出
// "DELETE QUERY";
//5
// "INSERT QUERY";
// "DELETE QUERY";
//2
// "INSERT QUERY";
依旧......
但我得到的是
// "DELETE QUERY";
//5
// "DELETE QUERY";
//5 //not fetching the next array val
// "INSERT QUERY";
// "INSERT QUERY";
任何帮助都很受欢迎。
修改
从答案我更新了这样的代码
现在代码看起来像这样
aysnc.forEach(results, function(elem, callback){
target_user = elem.id
console.log('out')
console.log(target_user)
con.query(sql, function (err) {
if (err) throw err;
console.log('in')
console.log(target_user)
})
})
奇怪的是,输出是
out
5
in
5
out
2
in
5 //when it is supposed to be 2
答案 0 :(得分:2)
您仍然可以以不同的方式使用npm模块async
const mysql = require('mysql');
const async = require('aynsc');
var db; //database variable
async.series([
//creates DB connection and connects
function(callback){
db = mysql.createConnection(DB_INFO); //DB_INFO is an Object with information on the BD to be connected
db.connect(function(err){
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(); //goes to the next function
});
},
//performs the Query 1
function(callback){
db.query('QUERY1', function(){
callback(); //goes to the next function
});
},
//performs the Query 2 only after Query 1 is finished
function(callback){
db.query('QUERY2', function(){
db.end(); //closes connection
callback();
});
}
]);
答案 1 :(得分:1)
在node.js中, FOR 循环将并行执行,因此使用 async 模块或 PROMISE 是使用 async的示例强>
var async = require('aynsc');
con.query(sql, function (err, results) {
if (err) throw err;
// ids => 5,2,3,4
async.forEach(results, function(elem, callback){
target_user = results[i].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
callback()
})
})
}, function(err){
//final callback once loop is done
});
})
答案 2 :(得分:1)
您可以使用递归来解决这样的问题。继续调用函数,直到结果中没有元素
con.query(sql, function (err, results) {
if (err) throw err;
deleteAndInsertResults(results);
})
function deleteAndInsertResult(results)
{
target_user = results[0].ID
var sql = "DELETE QUERY";
con.query(sql, function (err) {
if (err) throw err;
console.log(target_user)
var sql = "INSERT QUERY";
console.log(sql)
con.query(sql, function (err) {
if (err) throw err;
results.shift();
if(results.length){
return deleteAndInsertResult(results);
}
})
})
}