在下面的代码中,我注意到了一个使我感到困惑的异常。打印字符串“ 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);
答案 0 :(得分:1)
NodeJs本质上是Aysnc,如果正在执行异步任务,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) {
///
});
此部分正在执行数据库I / O操作,NodeJ将其推入堆栈并执行下一条语句console.log("somestr is " + somestr + "end somestr");
现在,当数据库调用完成时,它将执行相应的块。 console.log('entryname is ' + entry.name);