对返回promise的函数使用.success时,Undefined不是函数

Undefined is not a function when using .success on a function that returns a promise

本文关键字:函数 Undefined success 返回 promise      更新时间:2023-09-26

我正试图通过编写登录函数来继续理解promise。Login函数是AuthService的一部分,它向我的服务器发送http请求并返回promise(如果验证了用户,则promise得到解决,如果未验证则拒绝)。

当调用我的控制器中的函数时,我尝试使用.success和.error,因为该函数返回了一个promise,但我得到了错误"Undefined is not a function"。

这是我的函数,它获取未定义的错误。

$scope.login = function(email, password) {
  return AuthService.login(email, password).success(function(data) {
    return console.log("login function returned", data);
  }).error((function(data) {
    return console.log("There was an error " + data);
  }));
};

这是我的服务

.service('AuthService', function($window, $rootScope, $q, $http) {
  return {
    login: function(email, password) {
      var deferred;
      deferred = $q.defer();
      $http.post('/dashboard/login', {
        email: email,
        password: password
      }).error(function(error, status) {
        console.log("Incorrect logi");
        return deferred.reject(error);
      }).success(function(data, status) {
        $window.sessionStorage["userInfo"] = JSON.stringify(data);
        return deferred.resolve(data);
      });
      return deferred.promise;
    }
  };
});

最让我困惑的是,经过研究,promise似乎没有成功或错误的方法,但$http是一个有这种方法的promise。同样,如果他们没有成功和错误,你怎么知道某件事是不是错误?最后,如果没有成功或错误的方法,那么拒绝和解决有什么意义?

最让我困惑的是,经过研究,promise似乎没有成功或错误的方法,但$http是一个有方法的promise

是的,的确如此。$http返回对象是由于遗留原因具有这些.success.error方法的承诺。

如果他们没有成功和错误,你怎么知道某件事是不是错误?

将处理程序附加到promise的标准方法是使用.then()方法,该方法也充当链接方法,并为处理程序的结果返回一个新的promise。

因此,代码看起来是这样的(也避免了延迟的反模式):

.service('AuthService', function($window, $rootScope, $q, $http) {
  return {
    login: function(email, password) {
      return $http.post('/dashboard/login', {
        email: email,
        password: password
      }).then(function(data, status) {
        $window.sessionStorage["userInfo"] = JSON.stringify(data);
        return data;
      }, function(error, status) {
        console.log("Incorrect login");
        throw error;
      });
    }
  };
});
$scope.login = function(email, password) {
  return AuthService.login(email, password).then(function(data) {
    return console.log("login function returned", data);
  }, function(err) {
    return console.log("There was an error " + err);
  });
};