I'm new to the world of promises and I'm not sure I fully understand how to use them in some cases.
Sequelize recently added support for promises, which really makes my code more readable. A typical scenario is to avoid handling errors several times in infinite callbacks.
The snippet below always return 204
, while I'd like it to return 404
when the photo cannot be found.
Is there a way to tell Sequelize to "stop" the execution of the promise chain after sending 404? Note that res.send
is asynchronous so it does not stop the execution.
// 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);
});
Of course this example is trivial and could easily be written with callbacks. But in most cases the code can become way longer.