Return rows with nodejs and node-mysql

半城伤御伤魂 提交于 2019-11-30 21:30:27
robertklep

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!