0

I am having an issue returning results from a Express JS model. I think my problem is a lack of understanding of callbacks and JS Classes. I just can't seem to make it work.

I have the following code.

From the server.js I have this route:

app.get('/api/v1/loralocations/:id', LoraLocation.getOne);

Which calls the Controller action below

getOne(req, res) {
  const lora_location = LoraLocationModel.findOne(req.params.id);
  if (!lora_location) {
    return res.status(404).send({'message': 'LoraLocation not found'});
 }
 return res.status(200).send(lora_location);
},
.
.
.

Model

var pool = require('./mysqlDb.js');
import moment from 'moment';

class LoraLocation {  
  /**
   * class constructor
   * @param {object} data
   */
  constructor() {

  }

findOne(id) {
    var sql = ('SELECT test FROM Test WHERE id = ?');
    pool.query(sql, [id], function (err, results, fields) {
      if (err) return err;  
      console.log(results); //works
      return results; //nope
    });
  }

The console.log returns the results, but nothing is returned to the controller. I have gone through a number of posts but can't seem to find a solution. I think maybe I need a callback in the controller also?

Would this be a fairly standard pattern for a simple API project?

Thanks

Smithy
  • 5
  • 3
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Jan 03 '20 at 07:37

1 Answers1

0

You are using callback incorrectly. either you can use async/await which is a good option or if you want to stick with callbacks then you need to return callback function.

controllers

const lora_location = LoraLocationModel.findOne(req.params.id, function (err, data) => {
});

in the model it should be

findOne(id, cb) {
    var sql = ('SELECT test FROM Test WHERE id = ?');
    pool.query(sql, [id], function (err, results, fields) {
      if (err) cb(err, []);  
      console.log(results); //works
      cb(null, results);
    });
  }

you can get more details for callbacks in this link https://medium.com/better-programming/callbacks-in-node-js-how-why-when-ac293f0403ca

salman
  • 264
  • 1
  • 9
  • Great - Thanks this got me going after removing function from `function (err, data) => {` I'll look into async/wait (promises?) – Smithy Jan 03 '20 at 09:40