简体   繁体   English

从函数node.js / MySQL的内部函数返回值

[英]Return value from inner function of a function node.js / MySQL

I'm working on a very simple web app that doesn't do much, however it does connect to a database for INSERT and SELECT operations on one table. 我正在一个非常简单的Web应用程序上工作,该应用程序并没有做很多事情,但是它确实连接到数据库以在一个表上执行INSERT和SELECT操作。 I have a function that I utilized while browsing through several great tutorials, however I'm having trouble returning the rows from the SELECT query. 浏览一些出色的教程时,我使用了一个函数,但是我无法从SELECT查询返回rows Keeping in mind I'm learning Node.JS -- how would I display the data returned from the query (SELECT) to this block? 紧记我正在学习Node.JS-如何显示从查询(SELECT)返回的数据到此块?

app.post("/getcsv", function(req,res){

var sqlselall = "SELECT * FROM office";
var rows = handle_database(sqlselall);
res.json(rows);
res.end();

The function for handling the database connections (using pooling): 处理数据库连接(使用池)的功能:

function handle_database(sqlstmt){

pool.getConnection(function(err,connection){

    if(err) {
        res.json({"code" : 100, "status" : "Error in connection to database."});
        return;
    }

    console.log('connected as id ' + connection.threadId);

    connection.query(sqlstmt, function(err,rows){
        connection.release();
        if(!err){
            console.log("Number of rows affected: " + rows.affectedRows);
        }

    });

    connection.on('error', function(err) {
        res.json({"code": 100, "status" : "Error in connection to database."});
        return;
    });

I realize that the rows in the inner function contains the data I need, however I'm at a loss as to how to return it when I call the function. 我意识到内部函数中的rows包含了我需要的数据,但是当我调用函数时如何返回它是一个困惑。

So if I could have commented on you answer I would have. 因此,如果我能对您的回答发表评论,我将拥有。 This is something that I would like to supplement to your answer, because it looks like your answer should work to me, although I have not tested it personally. 我想对您的答案做些补充,因为尽管我没有亲自测试过,但看起来您的答案应该对我有用。

From experience of trying to learn the callback style I think this might help you. 根据尝试学习回调样式的经验,我认为这可能会对您有所帮助。 It does help keep the code a little more modular. 它确实有助于使代码更具模块化。

app.post("/getcsv", function(req, res) {
   var sqlselall = "SELECT * FROM office"
   select_query(sqlselall, function(results){
      res.send(results)
   })
})

function select_query(sqlstmt, callback) {
  pool.query(sqlstmt, function(err, results, fields) {
  //I suppose if this is how you want to handle errors
  //for debugging purposes I like returning them as well
  //returning it helps both you and others who might be working on
  //the front end to know whats happening
  if (err) throw err
  callback(JSON.stringify(results))
  })
}

This way your select_query function doesn't require the res to get passed in, and doesn't rely on a parameter that has a function in order to work. 这样,您的select_query函数不需要传入res,并且不依赖具有该函数的参数才能正常工作。 Some times that cant be helped, but when it can I find its easier for maintenance to take that into account. 有时候这是无济于事的,但是当我可以找到时,考虑到它的维护比较容易。

In the hypothetical situation that you might have another end point that needs to query as well, but needs to append modify the information before you send it, you would still be able to use your select_query function, and just modify your callback that you pass into it. 在假设的情况下,您可能还有另一个端点需要查询,但需要在发送信息之前附加修改信息,您仍然可以使用select_query函数,只需修改传递给的回调它。 So you would end up with something like this: (I also changed the error handling a little) 因此,您最终会遇到这样的事情:(我也稍微修改了错误处理)

app.post("/getcsv", function(req, res) {
   var sqlselall = "SELECT * FROM office"
   select_query(sqlselall, function(err, results){
      if(err){
         res.send(err)
         //throw an error if you would like to here 
      }
      res.send(results)
   })
})
app.post("/modifyCSV", function(req, res){
  var sql = "{sql statement}"
   select_query(sql, function(err, results){
     if(err){
         res.send("Aww an error: "+err)
         //throw an error if you would like to here 
     }res.send(reuslts + "\nHello to you too")
   })
})

function select_query(sqlstmt, callback) {
  pool.query(sqlstmt, function(err, results, fields) {
  if (err) 
     callback(JSON.stringify(err), null)
  callback(null, JSON.stringify(results))
  })
}

Like I said, I am not saying your way is wrong, it works, and perhaps it will work better for you. 就像我说的那样,我并不是说您的方式是错误的,它可以工作,也许对您来说会更好。 I have just found that this helped me get a handle on callbacks, and actually start to enjoy using them. 我刚刚发现,这有助于我掌握回调,并真正开始喜欢使用它们。

Answering my own question, especially considering some may consider it a duplicate (which due to my lack of knowledge in regards to Node.JS and JS in general is likely), seems inappropriate, however I discovered that once I did some research (thanks @Paul - and callback hell) and gained clarification on some fundamentals regarding functions, callbacks, anonymous functions, and the nature of a function's scope in Javascript I was able to come up with a solution to my problem. 回答我自己的问题,尤其是考虑到某些问题可能会认为它是重复的(由于可能我缺乏对Node.JS和JS的了解,这似乎是不合适的),但是我发现,一旦我做了一些研究(感谢@ Paul-和回调地狱),并获得了有关函数,回调,匿名函数以及Javascript中函数作用域的性质的一些基础知识,我得以提出解决问题的方法。 So for my connection to the DB I created a new simplified function which is passed the parameter 'res' from the callback parameter (which I now somewhat understand) from app.post: 因此,对于我与数据库的连接,我创建了一个新的简化函数,该函数从app.post的回调参数(现在我已经有所了解)传递了参数“ res”:

app.post("/getcsv", function(req, res) {

  var sqlselall = "SELECT * FROM office"
  var thisData = select_query(sqlselall, res)
})

function select_query(sqlstmt, res) {

  pool.query(sqlstmt, function(err, results, fields) {
    if (err) throw err
    res.send(JSON.stringify(results))
  })
}

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

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