Is this a “Deferred Antipattern”?

后端 未结 3 1578
日久生厌
日久生厌 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:09

    Is this a “Deferred Antipattern”?

    Yes, it is. 'Deferred anti-pattern' happens when a new redundant deferred object is created to be resolved from inside a promise chain. In your case you are using $q to return a promise for something that implicitly returns a promise. You already have a Promise object($http service itself returns a promise), so you just need to return it!

    Here's the super simple example of what a service, with a deferred promise and one with antipattern look like,

    This is anti-pattern

    app.factory("SomeFactory",['$http','$q']){
        return {
            getData: function(){
                var deferred = $q.defer();            
                $http.get(destinationFactory.url)
                  .then(function (response) {        
                     deferred.resolve(response.data);
                })
                  .catch(function (error) {
                    deferred.reject(error);
                });            
                return deferred.promise;
            }
         }
    }])
    

    This is what you should do

    app.factory("SomeFactory",['$http']){
        return {
            getData: function(){
               //$http itself returns a promise 
                return $http.get(destinationFactory.url);
            }
    }
    

    while both of them are consumed in the same way.

    this.var = SomeFactory.getData()
        .then(function(response) {
            //some variable = response;
        },function(response) {
            //Do error handling here
    });
    

    There's nothing wrong with either examples(atleast syntactically)..but first one is redundant..and not needed!

    Hope it helps :)

提交回复
热议问题