javascript - 调试打印没有按顺序发生
问题描述
在下面的代码中,我注意到了一个令我困惑的异常情况。打印字符串“entryname”在“somestr”打印字符串之前执行。我可以知道为什么会这样吗?
var somestr = "";
con.query(
'SELECT name,areaid, panellabel,voltageid,installationtypeid from installation, (SELECT companyid from building where name="' +
req.body.location +
'")as company where installation.id=company.companyid',
function(err, rows, fields) {
if (err) throw err;
var output = JSON.parse(JSON.stringify(rows));
var arr = [];
console.log(rows);
output.forEach(function(entry) {
console.log("entryname is " + entry.name);
somestr =
somestr +
"<TR><TD>" +
entry.name +
"<TD>" +
entry.areaid +
"<TD>" +
entry.areaid +
"<TD>" +
entry.panellabel +
"<TD>" +
"<TD>" +
entry.voltageid +
"<TD>" +
entry.installationtypeid;
console.log(somestr);
});
}
);
console.log("somestr is " + somestr + "end somestr");
tablehead = tablehead + somestr;
console.log(somestr);
res.send(tablehead);
解决方案
NodeJs 本质上是 Aysnc,如果 Async 任务正在执行,NodeJS 会将代码推送到堆栈并执行下一个可用语句。
同样的事情也发生在这里..
con.query('SELECT name,areaid, panellabel,voltageid,installationtypeid from installation, (SELECT companyid from building where name=\"' + req.body.location + '\")as company where installation.id=company.companyid', function (err, rows, fields) {
///
});
由于本节正在执行 db I/O NodeJs 正在将其推送到堆栈并执行下一条语句console.log("somestr is " + somestr + "end somestr");
现在当 db 调用完成时,它将执行相应的块。console.log('entryname is ' + entry.name);
推荐阅读
- highcharts - Stacked Bar Highcharts 如何显示值
- java - 是否可以在 ingiteRepository 中使用“findbyId”方法?
- flutter - 如何在颤动的图像上设置具有不同文本的编辑文本?
- postgresql - 构造数组文字作为 PL/pgSQL 函数的输入
- c# - 如何在 wpf 中制作单行 tabitems 标题?
- php - 使用 PHP $_GET[ 在同一个 PHP 文件中显示不同的内容 - 还有其他方法吗?
- python - 在装饰器中访问 kw 参数的默认值?
- caching - 如何阻止 Windows Server 2019 上的 iisnode 缓存我的 javascript 文件?
- java - 特殊字符在编写 xml 时会产生问题
- php - 如何在大文件中的最后一个字符之前插入字符串