Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular promises run conditionally

I'd like to perform an asynch function conditionally, but I think I'm missing the correct syntax to say what I want.

this.doUpToThreeThings = function(skipTheMiddleStep) {
    return doFirstThing().then(function (result) {
        if (skipTheMiddleStep) {
            return doThirdThing();
        } else {
            return doSecondThing();
        }
    }).then(function (result) {
        if (skipTheMiddleStep) {
            return "ok"; // return what?
        } else {
            return doThirdThing();
        }
    });
}

By the time we get to the second then, I don't know if the first block did the middle step, so I'm forced into repeating the condition. And the second block reads weird: it should say, if skip the middle step, then do the third thing, but since it we know that the previous block must have done the third thing, it just returns. So I have to repeat the condition and write pretty wrong-looking code in the second then.

I realize I can write a function called doSecondAndThirdThings, and just call that from the condition in the first block, but that's not really DRY, it's just hiding the non-DRYness. (or maybe I'm wrong about that?)

Also, I'm still a little confused about returning a completed promise on that "ok" branch. Is that right how it is, or should I say something like resolve? -- Thanks

like image 573
goodson Avatar asked Mar 21 '23 03:03

goodson


1 Answers

The deferred in thefourtheye's answer is pointless and is considered an anti pattern with promises.

Here is how I would do it:

this.doUpToThreeThings = function(skipTheMiddleStep) {
    return doFirstThing().then(function (result) {
        return (skipTheMiddleStep) ? doThirdThing() : doSecondThing().then(doThirdThing);
    });
}
like image 114
Benjamin Gruenbaum Avatar answered Mar 29 '23 17:03

Benjamin Gruenbaum