Angular promises run conditionally

2019-05-06 15:33发布

问题:

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

回答1:

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