4 ms·
Chaining and returning can keep things nice and neat. Say you are following a Controller -> Service -> Repo implementation. Controller calls the service. Serv
by thealfreds 10y ago
Chaining and returning can keep things nice and neat. Say you are following a Controller -> Service -> Repo implementation.
Controller calls the service.
Service returns a call to a repo with any mapping that needs to occur.
Repo calls out to database or external api and returns the promise.
Makes the work very boring and repetitive for the most part which is a good thing I think.
function someController(req, res) {
UserService.getUser(req.session.user)
.then(SomeService.getSomething)
.then((val) => res.json(val))
.catch(handleError);
}
function getSomething(user) {
return SomeRepo.getSomething(user)
.then(MapSomething)
.catch(alternativeHigherLevelCatch);
}
function getSomething(user) {
return new Promise((resolve, reject) => {
database.getSomething(
'defined parameters',
user,
resolve,
reject
)
});
}
- rhinoceraptor 10y agoIt's trivial to refactor that code to use only callbacks, without ending up with callback hell. You certainly want to call UserService.getUser for many different controllers. Why manually do that for each controller? Simply make a middleware to get the user. If you take this to its logical conclusion, you end up with small, composable middleware functions, and controllers that are pure functions.
- thealfreds 10y agoWell sure with a single service and a single mapper etc. Once you start tacking on multiple it keeps following the pattern above with promises and just extends with `.then`'s. Also agree middleware is a good solution which can go through and provide a user object directly onto the request or another level of abstraction created if you prefer. That was simply to show how multiple service calls could be easily tied together rather than a full and usable example. A benefit of callbacks though, at least from my experience, is error messages when testing with mocha / chai. I only have experience with jasmine, mocha, and chai but the errors when test driving were much easier to follow with callbacks.