简体   繁体   English

Node JS MySQL查询函数不返回结果

[英]Node JS MySQL query function not returning result

I am running a MySQL query inside a .js file running on Node JS.我在 Node JS 上运行的 .js 文件中运行 MySQL 查询。 I have the connection setup ok and the query works but when I try returning the result back to the original call it doesn't seem to work.我的连接设置正常并且查询有效,但是当我尝试将结果返回到原始调用时,它似乎不起作用。

 function sqlQuery(query){ console.log("Running query"); var conn = connection(); var result = false; conn.query(query, function(err, rows, fields) { conn.end(); if (!err){ result = rows; } else { result = err; } }); return result; } var loginResult = sqlQuery("SELECT * FROM `players`"); console.log(loginResult);

If I use the following code it does write the result to the console inside the query but not the final "loginResult".如果我使用以下代码,它会将结果写入查询内的控制台,但不会将最终的“loginResult”写入。 I am not getting any errors so my question is - is there an error in the way I am getting the returned result?我没有收到任何错误,所以我的问题是 - 我获取返回结果的方式是否有错误?

 if (!err){ result = rows; console.log(rows); } else { result = err; }

Virtually everything in Node.js is asynchronous, and SQL query functions definitely are. Node.js 中的几乎所有东西都是异步的,SQL 查询函数肯定是异步的。 You're calling conn.query(query, callback) , which means that query is called, and then once there is a result at some point in the future, your callback function gets called with the result for you to work with.您正在调用conn.query(query, callback) ,这意味着调用了查询,然后一旦在将来的某个时刻有结果,您的回调函数就会被调用,并带有结果供您使用。 So:所以:

conn.query(query, function runThisEventually(err, rows, fields) {
    if (err) {
      console.error("One or more errors occurred!");
      console.error(err);
      return;
    }
    processResults(rows, fields);
});

You won't get the result immediately after calling conn.query(...) , so your code gets to do "other things" in the mean time, and at some point, your callback will be triggered and you can pick up result processing there.您不会在调用conn.query(...)后立即获得结果,因此您的代码同时可以做“其他事情”,并且在某个时候,您的回调将被触发,您可以获取结果在那里处理。

conn.query(query, function(err, rows, fields) {
    if (err) 
        console.log("error ocurred",err);
    res.send({
        "code":400,
        "message":"error ocurred"
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM