Search code examples
node.jsexpressnode-mysql

How to handle database delay on node-mysql when calling method from another js script


I'm doing a sample API using routes and controllers (with mysql as backend) for courses but one of my methods doesn't work as expected but I'm not sure why... this is my code so far.

This is routes/courses.js (when I go to localhost/courses, the application calls this):

var express = require("express");
var router = express.Router();

var coursesController = require("../controller/courses");

/* GET courses listing. */
router.get("/", function (req, res, next) {
  res.json(coursesController.getAllCourses()).status(200).end();
});

module.exports = router;

And this is my controller/courses.js

const mysqlPool = require("../db/database");

var Courses = {
  getAllCourses: () => {
    var sql = "select * from courses";
    var res = null;
    mysqlPool.getConnection((err, conn) => {
      if (err) throw err;
      try {
        conn.query(sql, (error, results) => {
          res = results;
          console.log(error);
          console.log(results);
          console.log("returning res = "+res)
          return res;
        });
      } catch (error) {
        throw error;
      }
    });
    console.log("not returned anything")
  },
  getSomeCourses: () => {},
};

module.exports = Courses;

I'm not sure why this doesn't work as expected. The database connection works OK, and it gets the results, but when I try to put them in a json, I only have a blank screen. Is it something I am missing? Maybe some async functionality or something like that?

These are the console.log results:

  mycourses:server Listening on port 3000 +0ms
not returned anything
GET /courses 200 14.548 ms - -
null
[
  RowDataPacket {
    idcourse: 1,
    name: 'Whatever 101',
    description: 'A course about nothing',
    thumbnail: null,
    price: 10.99
  },
  RowDataPacket {
    idcourse: 2,
    name: 'Anything 101',
    description: 'Course about idk',
    thumbnail: null,
    price: 9.99
  }
]
returning res = [object Object],[object Object]

Solution

  • You definitely need to turn getAllCourses into async function (use new Promise) and then in a route handler change your code like this:

    router.get("/", function (req, res, next) {
      coursesController.getAllCourses().then(courses => {
        res.json(courses); // there is no need to use status(200) and res.end if you use res.json
      });
    });
    
    

    Don't forget to add an error handler for all routes or add catch call after then to handle errors while getting courses from DB