Here is a controller content in the context of a nodejs app:
var express = require('express'),
directory_router = express.Router(),
directory_models = require('./directory_models');
directory_router.get('/list', function(req, res) {
var data = directory_models.read_result(function (err, data) {
console.log(data); // Need returned data here, but won't run
res.send(data); // Same
});
// If I try to access 'data' here it's empty
});
module.exports = directory_router;
And here is the model that returns the data it fetched in the database:
var settings = require('../../settings');
var read = function() {
var read_result;
settings.pg.connect(settings.conString, function (err, client, done) {
client.query('SELECT link_title FROM links', function (err, result) {
read_result = result.rows[0].link_title;
console.log('from model');
return read_result;
});
});
};
module.exports.read_result = read;
The problem is in the controller, I can't find anyway to have the 'data' console.log or res to run. And if I put them outside of the function, they run before the data is returned and thus are undefined. How to properly format the model code, to properly be able to access 'data' after result are returned from the model ? And is it recommended to use a module such as 'async' or 'promise' to handle such situation ?