簡體   English   中英

停止在Express.js中執行Sequelize承諾

[英]Stop execution of a Sequelize promise in Express.js

我是承諾世界的新手,我不確定我是否完全理解在某些情況下如何使用它們。

Sequelize最近增加了對promises的支持,這確實使我的代碼更具可讀性。 典型的情況是避免在無限回調中多次處理錯誤。

下面的片段總是返回204 ,而當我無法找到照片時,我希望它返回404

有沒有辦法告訴Sequelize在發送404后“停止”執行承諾鏈? 請注意, res.send是異步的,因此它不會停止執行。

// Find the original photo
Photo.find(req.params.id).then(function (photo) {
    if (photo) {
        // Delete the photo in the db
        return photo.destroy();
    } else {
        res.send(404);
        // HOW TO STOP PROMISE CHAIN HERE?
    }
}).then(function () {
    res.send(204);
}).catch(function (error) {
    res.send(500, error);
});

當然這個例子很簡單,很容易用回調寫。 但在大多數情況下,代碼可能變得更長。

您的承諾鏈不一定必須是線性的。 您可以“分支”並為成功案例創建單獨的承諾鏈,根據需要鏈接盡可能多的.then() ,同時為失敗案例設置單獨的(更短的)承諾鏈。

從概念上講,這看起來像這樣:

         Photo.find
          /     \
         /       \
    (success)   (failure)
       /           \
      /             \
photo.destroy    res.send(404)
     |
     |
res.send(204)

在實際代碼中,看起來像這樣:

// Find the original photo
Photo.find(req.params.id).then(function (photo) {
    if (photo) {
        // Delete the photo in the db
        return photo.destroy().then(function () {
            res.send(204);
        });
    } else {
        res.send(404);
    }
}).catch(function (error) {
    res.send(500, error);
});

暫無
暫無

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

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