Working with promises inside an if/else

后端 未结 10 1015
北恋
北恋 2021-02-02 10:46

I have a conditional statement in which I need to perform one of two operations, then continue after whichever operation has resolved. So my code currently looks as follows:

10条回答
  •  既然无缘
    2021-02-02 11:44

    The way I would do it would be to put the if check into another function that returns a promise. The promise gets resolved with the resolve of the other function calls in the if-else statement.

    Example:

    function performCheck(condition) {
        var defer = $q.defer();
        if (condition) {
            doThingA().then(function(response) {
                defer.resolve(response);
            });
        } else {
            doThingB().then(function(response) {
                defer.resolve(response)
            });
        }
        return defer.promise;
    }
    performCheck(condition).then(function(response) {
        //Do more code.
    });
    

    In my opinion, I would prefer this method because this function can now be used in multiple places where you have a check on the condition, reducing code duplication, and it is easier to follow.

    You could reduce this down further with

    function performCheck(condition) {
        var defer = $q.defer();
        var doThisThing = condition ? doThingA : doThingB;
        doThisThing().then(function (response) {
            defer.resolve(response);
        });
        return defer.promise;
    }
    performCheck(condition).then(function(response) {
        //Do more code.
    });
    

提交回复
热议问题