I have an Express app built with the Yeoman Angular fullstack generator to build an API to send JSON to Angular.
I’m trying to work out the best way to pass back information from my model to my controller, further processing may occur in the controller. I’m currently using promises. I feel uncomfortable about my model returning a promise to the controller. Should I?
Currently my Model looks like this:
function returnCountries(lim, offset) {
var promise = new Promise(function(resolve, reject) {
//SQL is just an example
connection.query('SELECT * FROM countries LIMIT 1', function(err, result) {
return resolve(result);
});
})
return promise
}
function returnCountry(countryID) {
//not yet implemented
}
module.exports = {
"returnCountries": returnCountries,
"returnCountry": returnCountry
}
And controller looks like this:
var Country = require('./country.model');
// Get list of countries
exports.index = function(req, res) {
Country.returnCountries().then(function(countries){
return res.json(200, countries);
})
Wouldn’t it be simpler to pass the callback to connection.query
around?
// model
function listCountries(limit, offset, callback) {
// SQL is just an example
connection.query('SELECT * FROM countries LIMIT 1', callback);
}
// controller
var Country = require('./country.model');
exports.index = function(req, res) {
var limit, offset;
Country.listCountries(limit, offset, function(error, result) {
// TODO: handle error
return res.json(200, result);
});
};
Unless your controller has much more async work to do; then promises would probably make sense for avoiding callback hell. Maybe using just one promise is what’s making you uncomfortable, it kind of seems like overkill at this point.