weixin_33674437 2016-08-08 20:22 采纳率: 0%
浏览 13

通过承诺返回错误

I am pretty new to AngularJS and Javascript. I am creating a app in which I am planning to use one function to do all ajax related operation(factory in angularjs). This function will be only one gateway for all ajax operations. When I return promise as a success it works properly. but returning error promise do not work.

Here is a sample code. I am expecting return of promise in error function if promise fails but it goes to success

var myApp = angular.module('myApp', []);

myApp.controller('FirstController, function($scope, util){
        util.doAjax().then(function(response){
                // This function is called in both success and error
            }, function(err){
                // This is never called why ?                
            });
});

myApp.factory('util, function($http){
    return $http({
       method: 'GET',
       url: 'http://www.example.com'
    }).then(function(response){
        // This will return success promise
        return response;
    }, function(err){
        // This should return error promise
        return err;
    });
});
  • 写回答

2条回答 默认 最新

  • weixin_33696822 2016-08-08 20:24
    关注

    Currently you are directly returning a data from error function, which is chaining the promise and calling it underlying .then method.

    While returning an error you have to reject a promise by creating a new custom promise using $q

    return $q.reject(err)
    

    Other important thing is, you should create method in a service with name

    myApp.factory('util', function($http, $q){
     //Exposed method
     return {
       doAjax : function() {
           return $http({
              method: 'GET',
              url: 'http://www.example.com'
           }).then(function(response){
               // This will return success promise
               return response.data; // returned data
           }, function(err){
               // return error promise with err object
               return $q.reject(err);
           });
         }
      }
    });
    
    评论

报告相同问题?