Angular promises run conditionally

南楼画角 提交于 2019-12-22 08:25:13

问题


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


来源:https://stackoverflow.com/questions/22594978/angular-promises-run-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!