For example,
Comments.findOne({user: req.user.id}).exce()
.then(function(comment) {
if(comment) {
// how to make this return immediately and break the rest then?
return res.json({error: 'Already commented'});
} else {
return Posts.findOne({postId: req.params.id}).exec();
}
})
.then(function(post) {
if(post) {
var comment = new Comment({user: req.user.id, data: req.body.comment})
return {post: post, comment: comment.save()};
} else {
return res.json({error: 'Post not exist'});
}
})
.then(function(data) {
post.comments.push(comment._id);
return post.save();
});
.then(function(post) {
return res.json({ok: 1})
})
.catch(function(e)) {
return res.json(error: e);
});
Is this promise written right? How to write this kind of promise? Callbacks/Promises is a headache...
You just need to throw
or return a reject promise to trigger the error handling in promises as show in this example:
Comments.findOne({user: req.user.id}).exce()
.then(function(comment) {
if(comment) {
// to bypass all the other .then() resolve handlers, either
// throw an error here or return a rejected promise
throw new Error(res.json({error: 'Already commented'}));
} else {
return Posts.findOne({postId: req.params.id}).exec();
}
})
Promises are "throw safe" which means that .then()
will catch any exception thrown and turn it into a rejected promise. This will bypass any following .then()
resolve handlers and will instead go to the next reject
handler or .catch()
handler.
FYI, you should be careful in your code because when you .catch()
and then just return from that, it changes your promise state from rejected to resolved and it will then look like a successful promise when you actually had an error and any caller will think everything was successful. This is because the promise infrastructure assumes that if you .catch()
an error and return a value that you have "handled" the error and the state is now resolved successfully. To allow the error to continue to propagate to higher callers from a .catch()
, you have to re throw or return a rejected promise:
blah(...).then(...)
.catch(function(e)) {
throw new Error(res.json(error: e));
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments