我有一连串的承诺,如下所示:
module.exports.deleteCommunityFollower = function deleteCommunityFollower(req, res){
var communityId = req.params.userId;
var followerId = req.session.passport.user.userId;
var community = new user_model.User(communityId);
community.getFollower(followerId)
.then(function(data) {
if(data.length === 0) {
res.sendStatus(404); //no follower found, interrupt execution
} else {
return community.removeFollower(data[0]); //returns a promise
}
})
.then(function() {
res.sendStatus(201); //follower removed, success
})
.fail(function(error) {
errorHelper.diagnosticsUploader(error, community);
res.sendStatus(500);
});
}
我的问题是关于线路的res.sendStatus(404)
。这是中断承诺链执行的正确且优雅的方式吗?背景是,有时在链接 Promise 时,我发现了类似这样的场景,您需要出于以下原因停止链的执行:不是错误。我知道我可能会犯人为错误data.length === 0
,但这对我来说看起来不优雅。
在上面的代码中,当data.length === 0
如果是 true,我只是返回一个 http 响应,而不向 Promise 解析器返回任何值,从而有效地阻止链执行继续。但是,我想验证这是否是推荐的做法。在我看来,中途留下一个承诺可能会成为未来的麻烦根源(内存泄漏?)
由于您使用的是现代节点,因此我将使用以下方式编写它Q.async https://github.com/kriskowal/q/wiki/API-Reference#qasyncgeneratorfunction:
const deleteFollower = Q.async(function*(communityId, followerId){
const community = new user_model.User(communityId);
let followers = yield community.getFollower(followerId);
if(followers.length) === 0; return false;
yield community.removeFollower(follower[0]);
return true;
});
读起来像一个同步函数并且完全平坦,很好吧?
我省略了从 req/res 中提取内容的代码,因为这会使代码更难以测试,并且无论如何都应该将其分开。我会这样称呼它:
function handler(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);
});
}
(注意,我个人更喜欢使用bluebird https://github.com/petkaantonov/bluebird出于性能原因,我会使用库Promise.coroutine
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)