How To (elegantly) Interrupt Promises Chain Execution With Q
I have a chain of promises that looks like this: module.exports.deleteCommunityFollower = function deleteCommunityFollower(req, res){ var communityId = req.params.userId; var f
Solution 1:
Since you are using modern node, here is how I would write it using Q.async
:
const deleteFollower = Q.async(function*(communityId, followerId){
const community = new user_model.User(communityId);
let followers = yield community.getFollower(followerId);
if(followers.length) === 0; returnfalse;
yield community.removeFollower(follower[0]);
returntrue;
});
Reads like a synchronous function and completely flat, nice huh?
I omitted the code extracting things from req/res since that would make the code harder to test and it should probably be separated anyway. I'd call it like:
functionhandler(req, res){
var communityId = req.params.userId;
var followerId = req.session.passport.user.userId;
deleteFollower(communityId, followerId).then(val => {
if(val) res.sendStatus(201);
else res.sendStatus(404);
}).fail(err => {
res.sendStatus(500);
errorHelper.diagnosticsUploader(err);
});
}
(Note, personally I much prefer using the bluebird library for performance reasons, where I'd use Promise.coroutine
).
Post a Comment for "How To (elegantly) Interrupt Promises Chain Execution With Q"