1

I'm new to using the bluebird promise library. And I was wondering if there was a better way to do wrap complex if then branching statements that may or may not require async calls than what I'm currently doing.

example of what I have now:

(function() {

    if (a) {
        return ModelA.findById(id);
    } else if (b) {
        return ModelB.findById(id);
    } else if (c) {
        return ModelC.findById(id);
    } else {
        return Promise.reject(new Error('a, b, or c must be specified'));
    }
})()
.then(function(result) {
    if(result == null) {
        return new Error('Object not found')
    }
    result.removedBy = user.id;
    result.removedWhen = new Date();
    result.inactive = true;
    return result.save();
})
C Deuter
  • 893
  • 1
  • 8
  • 14
  • 2
    I don't see much potential for improvement here. Of course, you might use ternary operators instead of the `if` (which would allow omitting the IIFE), and you could only distinguish the models but not the method call, but what you are doing is perfectly fine and readable. – Bergi Feb 25 '16 at 22:49
  • What exactly are `a`, `b` and `c`? – Bergi Feb 25 '16 at 22:55

1 Answers1

2

The only thing I would change is put it inside a .then:

Promise.resolve()
.then(function() {
    if (a) return ModelA.findById(id);
    if (b) return ModelB.findById(id);
    if (c) return ModelC.findById(id);
    throw new Error('a, b, or c must be specified');
})
.then(function(result) {
    if (!result) {
        return new Error('Object not found');
    }
    result.removedBy = user.id;
    result.removedWhen = new Date();
    result.inactive = true;
    return result.save();
})
.catch(e => console.error(e));

This has better error handling characteristics: You don't have to worry about both exceptions and rejections, and potential coding errors are dealt with the same way as other errors.

Being inside a .then has the added advantage of not worrying about always returning a promise (since anything returned is automatically wrapped in one), a nice invariant, and more readable too.

jib
  • 40,579
  • 17
  • 100
  • 158