Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have an Express app built with the Yeoman Angular fullstack generator to build

ID: 647840 • Letter: I

Question

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);
})

Explanation / Answer

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.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote