Thursday 26 May 2016

node.js - Correct way of handling promisses and server response

I am trying to improve my code in node.js / sail.js and I am fighting server response in promisses.



When you look at the first .then function you can see that method returns false in case of forbidden access or notFound. Then, in the next .then functions I must check if the return type is === false to skip to section and avoid sending http headers twice. Can this be improved somehow, to skip all next .then methods in case of failure? I can throw an Exception to go in the last .catch but then there must be a case to switch between all possible states. (i.e. forbidden, serverError or even not found)



Notification.findOne({id: req.param('id')})

.then(function(notification) {
if (!notification) {
res.notFound();
return false;
}

if (notification.triggeredBy != req.session.user.id) {
res.forbidden();
return false;
}


return notification;
})
.then(function(notification) {
if (notification === false) {
return false;
}

return Notification.update(notification.id, actionUtil.parseValues(req));
})

.then(function(notification) {
if (notification === false) {
return false;
}

res.json(notification);
})
.catch(function(err) {
sails.log(err);
res.serverError({message: 'A server error occurred.'});

})

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...