停止执行Express.js中的Sequelize承诺

我是新来的承诺的世界,我不知道我完全理解如何在某些情况下使用它们。

Sequelize最近添加了支持承诺,这使得我的代码更具可读性。 一个典型的情况是避免在无限callback中多次处理错误。 下面的代码总是返回204而当我无法find照片时,我希望返回404

有没有办法告诉Sequelize发送404后“停止”承诺链的执行? 请注意, res.send是asynchronous的,所以它不会停止执行。

 // 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); }); 

当然这个例子是微不足道的,可以很容易地用callback函数来写。 但在大多数情况下,代码可以变得更长。

你的承诺链不一定是线性的。 您可以“分支”并为成功案例创build一个单独的承诺链,并根据需要链接尽可能多的.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); });