我试图通过编写一个登录函数来继续我对 promises 的理解。 Login 函数是 AuthService 的一部分,它向我的服务器发送一个 http 请求并返回一个 promise (如果用户通过验证则该 promise 得到解决,否则将被拒绝)。
在我的 Controller 中调用该函数时,我尝试使用 .success 和 .error,因为该函数返回一个 promise ,但我收到错误“未定义不是函数”。
这是我得到未定义错误的函数。
$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;
}
};
});
最让我困惑的是,在研究之后,promises 似乎没有成功或错误方法,但 $http 是具有该方法的 promise。另外,如果他们没有成功和错误,您怎么知道是否有错误?最后,如果没有成功或错误方法,.reject 和 .resolve 有什么意义?
最佳答案
What confuses me most is that after researching it seems like promises don't have a success or error method but $http is a promise that has that method
是的,的确如此。 $http
返回对象是也由于遗留原因而具有这些.success
和.error
方法的 promise 。
if they don't have success and error how do you know if something is an error or not?
将处理程序附加到 promise 的标准方法是使用 .then()
method ,它也充当链接方法并为处理程序的结果返回新的 promise 。
所以代码看起来像这样(也是 avoiding the deferred antipattern ):
.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);
});
};
关于javascript - 在返回 promise 的函数上使用 .success 时,未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26521098/