Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop execution of a Sequelize promise in Express.js

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.

like image 934
Pedro Avatar asked Jun 06 '14 22:06

Pedro


1 Answers

Your promise chains don't necessarily have to be linear. You can "branch off" and create a separate promise chain for the success case, chaining on as many .then()'s as you need to, while having a separate (shorter) promise chain for the failure case.

Conceptually, that looks like this:

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

And in the actual code, that looks like this:

// 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);
});
like image 110
Sergey K Avatar answered Oct 14 '22 03:10

Sergey K