首页 > 解决方案 > 调试打印没有按顺序发生

问题描述

在下面的代码中,我注意到了一个令我困惑的异常情况。打印字符串“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);

标签: javascriptnode.js

解决方案


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);


推荐阅读