如何解决在NodeJS中将While循环与SQL请求一起使用
所以我试图使用while循环来遍历数组。我已经成功地获得了sql连接,可以使用不带while循环的代码来打印结果,因此我知道该查询有效,但是在while循环中它不起作用。
var sql = "SELECT algorithm FROM algorithms WHERE AlgorithmName = " + con.escape(PLLNames[0]);
con.query(sql,function (err,result) {
console.log("Sup")
if (err) throw err;
console.log("Result: " + result);
x+=1;
console.log(x)
});
res.render("PLL",{
algorithmTest: result,});
使用类似这样的方法可以正常工作,但是当我对其进行编辑以使其循环时,代码将中断。我知道它没有执行查询,因为它没有记录结果,也没有给出错误。由于某种原因,代码甚至没有尝试执行查询。这就是我试图做的事情
x = 0;
while (x < 20) {
var sql = "SELECT algorithm FROM algorithms WHERE AlgorithmName = " + con.escape(PLLNames[0]);
con.query(sql,result) {
console.log("Sup")
if (err) throw err;
console.log("Result: " + result);
x+=1;
console.log(x)
});
};
res.render("PLL",});
有人知道为什么会这样吗?
解决方法
发生此问题是因为con.query
不等待res.render
循环安排的sql查询,因此while
异步工作。您可以通过使用递归函数而不是while
循环来解决此问题:
function next(counter,limit,callback) {
if (counter >= limit) {
callback()
return;
}
var sql = "your SQL query";
con.query(sql,function (err,result) {
if (err) throw err;
console.log("Result: " + result);
counter+=1;
next(counter,callback);
});
}
next(0,20,function() {
res.render("PLL",{
algorithmTest: result,});
})
,
最好的解决方案是拥有一个堆栈,以保留应运行的内容。 我认为这个示例将帮助您入门,并且易于遵循和理解。
const stack = [];
let x = 0;
const results = [];
// Fill the stack
while (x < 20) {
// are you sure you don't want PLLNames[x] ?
stack.push("SELECT algorithm FROM algorithms WHERE AlgorithmName = " + con.escape(PLLNames[0]));
x++;
}
function worker() {
if(stack.length > 0) {
let sql = stack.shift();
con.query(sql,result) {
console.log("Sup")
if (err) throw err;
console.log("SQL: " + sql);
console.log("Result: " + result);
results.push(result);
worker();
});
} else {
// Not sure what you want to do with the results,but you got 20 of them so somehow you need to process it into one result.
res.render(JSON.stringify(results));
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。