Return rows with nodejs and node-mysql

后端 未结 1 647
小鲜肉
小鲜肉 2021-01-05 23:03

I\'m discovering Nodejs and the node-mysql module. I have a small problem. Every tutorial that I find explain how to do a select on the database but they never return the ro

1条回答
  •  抹茶落季
    2021-01-05 23:45

    query() is an asynchronous function from which you can't return any results. And consequently, any functions which call asynchronous functions themselves (like your findAllContinents) can't either.

    Instead, you need to pass a callback function (also explained here) which will be called when the query is done:

    // app.js
    app.get("/continents", function(request, response) {
      database.findAllContinents(function(err, results) {
        if (err)
          throw err; // or return an error message, or something
        else
          res.send(results); // as a demo, we'll send back the results to the client;
                             // if you pass an object to 'res.send()', it will send
                             // a JSON-response.
      });
    });
    
    // mysql.js
    exports.findAllContinents = function(cb) {
      var connection = getConnection();
      connection.query('select id, code, name from Continent', function (err, rows, fields) {
        // close connection first
        closeConnection(connection);
        // done: call callback with results
        cb(err, rows);
      });
    };
    

    As for (not) using an ORM, that really depends on the use case. I would choose an ORM (my favorite for MySQL is patio) in case my app requires multiple (complex) models, perhaps with associations between them. Also, the abstraction an ORM provides makes code more easy to read and usually allows to more easily port an app to a different database.

    0 讨论(0)
提交回复
热议问题