0

I am trying to make na MVC Express.js application skeleton, and I want to separate controllers from models. I can easily do this in the controller, or in model. But I would like to keep DB logic in models, and actually work on the data returned by the model in my controllers.

I have this piece of code (My Controller):

user.findById(78, function (err, result) {

console.log(result);
});

and the actualy findByID implementation (My Model):

Start.prototype.findById = function(id, callback) {
var queryString = 'SELECT * FROM users WHERE userId=' + "'" + id + "'";

 request.query(queryString, function (error, result) {

if (error) {
  return;
}
callback (result);
});

This is query toward the MsSQL server, and it either returns an error or result.

My question is how can I in the first code example actually receive back an error or the result. Right now there is no connection. Result is properly fetched in the second code, but it never gets returned to the caller function.

After some trying I come up with this idea, that apparently works. Is this the normal way of doing it, or do I need to change something?

Start.prototype.findById = function(id, callback) {
var queryString = 'SELECT * FROM users WHERE userId=' + "'" + id + "'";

 request.query(queryString, function (error, result) {

if (error) {
 callback (error);
}
callback (result);
});



 function doSomething(callback, id) {

    user.findById(id, callback);

    callback(result);
}

function foo(result) {        
    console.log(result);
}

doSomething(foo, 78);
Amiga500
  • 5,874
  • 10
  • 64
  • 117
  • `request.query(` runs asynchronously, you cannot return from it, see the answers on the dupe question to return data from async function. – Tushar Dec 18 '15 at 15:15
  • I have edited my question, I have also looked at the other examples, but really cant get my head around this. – Amiga500 Dec 18 '15 at 15:29
  • Create a function that'll accept the response from the query and process it, and in the callback of `request.query` call the function with response as param instead of returning the response – Tushar Dec 18 '15 at 15:30
  • Please, can you check my updated answer. The new code at the bottom. thanks for the tips :) – Amiga500 Dec 18 '15 at 15:58
  • Reopened, as not this is not dupe – Tushar Dec 18 '15 at 16:02
  • Of course its not a dupe – Amiga500 Dec 18 '15 at 22:23

0 Answers0