Dmi*_*ank 7 javascript promise angularjs angular-promise
承诺使用的模式仍然让我困惑.
例如,在Angular应用程序中,我有一个usersService带方法的服务emailExists(email).显然,它会向服务器执行请求,以检查给定的电子邮件是否已存在.
它感觉自然对我来说,使该方法emailExists(email)返回的承诺,在正常操作解析为true或false.如果我们只有一些意外错误(例如,服务器返回500: internal server error,则应拒绝承诺,但在正常操作中,它将被解析为相应的布尔值.
Hovewer,当我开始实现我的异步验证器指令(by $asyncValidators)时,我发现它想要解析/拒绝承诺.所以,到现在为止,我最终得到了这个相当丑陋的代码:
'use strict';
(function(){
angular.module('users')
.directive('emailExistsValidator', emailExistsValidator);
emailExistsValidator.$inject = [ '$q', 'usersService' ];
function emailExistsValidator($q, usersService){
return {
require: 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.emailExists = function(modelValue, viewValue){
return usersService.emailExists(viewValue)
.then(
function(email_exists) {
// instead of just returning !email_exists,
// we have to perform conversion from true/false
// to resolved/rejected promise
if (!email_exists){
//-- email does not exist, so, return resolved promise
return $q.when();
} else {
//-- email already exists, so, return rejected promise
return $q.reject();
}
}
);
};
}
}
};
})();
Run Code Online (Sandbox Code Playgroud)
它让我觉得我应该修改我的服务,以便它返回已解决/拒绝的承诺.但是,对我来说这感觉有点不自然:在我看来,被拒绝的承诺意味着" 我们不能得到结果 ",而不是" 负面结果 ".
或者,我是否误解了承诺的用法?
或者,我应该提供两种方法吗?命名它们的常见模式是什么?
任何帮助表示赞赏.
在这种情况下,这个问题没有正确/不正确的方法。您所说的有关电子邮件检查服务的内容听起来很有道理:事实上,数据库中存在电子邮件并不严格表示失败场景,承诺拒绝通常对应并反映。
另一方面,如果你仔细想想,Angular 实现异步验证器的方式也是有意义的。失败的验证结果在概念上感觉像是失败,不是在 HTTP 方面,而是在业务逻辑方面。
因此,在这种情况下,我可能会去调整我的自定义服务,至少返回非成功状态,例如409 Conflict。
如果您仍然想返回 200 个成功代码以及 true/false 响应,您仍然可以使验证器代码变得不那么难看:
ngModel.$asyncValidators.emailExists = function (modelValue, viewValue) {
return usersService.emailExists(viewValue).then(function (email_exists) {
return $q[email_exists ? 'when' : 'reject']();
});
};
Run Code Online (Sandbox Code Playgroud)