Is this a “Deferred Antipattern”?

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

    Using the $q constructor is a deferred anti-pattern

    ANTI-PATTERN

    vm.download = function() {
      var url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";    
      return $q(function(resolve, reject) {    
        var req = {
          method: 'POST',
          url: url,
          responseType: 'arraybuffer'
        };   
        $http(req).then(function(response) {
          resolve(response.data);
        }, function(error) {
          reject(error);
        });
      });
    }
    

    CORRECT

    vm.download = function() {
        var url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";    
        var req = {
          method: 'POST',
          url: url,
          responseType: 'arraybuffer'
        };   
        return $http(req).then(function(response) {
            return response.data;
        });
    }
    

    The $http service already returns a promise. Using the $q constructor is unnecessary and error prone.

提交回复
热议问题