Is this a “Deferred Antipattern”?

后端 未结 3 1447
日久生厌
日久生厌 2020-11-21 06:25

I\'m finding it hard to understand the \"deferred antipattern\". I think I understand it in principal but I haven\'t seen a super simple example of what a service, with a di

3条回答
  •  甜味超标
    2020-11-21 07:00

    I would say that it is the classic deferred anti-pattern because you are creating needless deferred objects. However, you are adding some value to the chain (with your validation). Typically, IMO, the anti-pattern is particularly bad when deferred objects are created for very little or no benefit.

    So, the code could be much simpler.

    $q promises have a little documented feature of automatically wrapping anything returned inside a promise in a promise (using $q.when). In most cases this means that you shouldn't have to manually create a deferred:

    var deferred = $q.defer();
    

    However, that is how the documentation demonstrates how to use promises with $q.

    So, you can change your code to this:

    return {
        getData: function(){
            return $http.get(destinationFactory.url)
                .then(function (response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        throw new Error('Error message here');
                    }
                });
    
                // no need to catch and just re-throw
            });
        }
    

提交回复
热议问题