简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM