簡體   English   中英

如何(優雅地)用Q中斷Promises鏈執行

[英]How to (elegantly) interrupt Promises chain execution with Q

我有一系列承諾,看起來像這樣:

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) 這是否是打斷承諾鏈執行的正確而優雅的方式? 背景是,有時當鏈接承諾時,我發現像這樣的場景,你需要停止鏈的執行,原因不是錯誤 我知道我可以在data.length === 0拋出一個人為錯誤,但這對我來說看起來不那么優雅。

在上面的代碼中,當data.length === 0為真時,我只返回一個http響應,並且不向promise解析器返回任何值,從而有效地防止鏈執行繼續。 但是,我想驗證這是否是推薦的做法。 留下一個掛在中途的承諾看起來像是它可能成為未來的麻煩(內存泄漏?)

由於您使用的是現代節點,因此我將使用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; 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庫,因為性能原因,我使用Promise.coroutine )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM