草庐IT

javascript - AngularJS : Should service's boolean method return promise that resolves to true/false, 或者被解决/拒绝?

coder 2024-07-26 原文

promise 的使用模式仍然让我感到困惑。

例如,在 Angular 应用程序中,我有一个服务 usersService,方法是 emailExists(email)。显然,它向服务器请求检查给定的电子邮件是否已经存在。

让方法 emailExists(email) 返回在正常操作中解析为 truefalse 的 promise 对我来说感觉很自然.如果只是我们有一些意外的错误(比如,服务器返回 500:内部服务器错误,那么 promise 应该被拒绝,但在正常操作中,它被解析为相应的 bool 值。

然而,当我开始实现我的异步验证器指令(通过 $asyncValidators)时,我看到它想要解决/拒绝 promise 。所以,到现在为止,我得到了这个相当难看的代码:

'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();
                     }
                  }
               );
            };
         }
      }
   };

})();

这让我觉得我应该修改我的服务,以便它返回已解决/拒绝的 promise 。但是,这对我来说感觉有点不自然:在我看来,拒绝 promise 意味着“我们无法得到结果”,而不是“负面结果”。

或者,我是否误解了 promise 的用法?

或者,我应该提供两种方法吗?命名它们的常见模式是什么?

感谢任何帮助。

最佳答案

在这种情况下,没有正确/不正确的方法来解决这个问题。您所说的关于您的电子邮件检查服务的说法听起来很合理:实际上,数据库中存在电子邮件并不严格表示失败场景, promise 拒绝通常对应并反射(reflect)。

另一方面,如果您考虑一下,Angular 实现异步验证器的方式也很有意义。失败的验证结果在概念上感觉像是失败,不是在 HTTP 方面,而是在业务逻辑意义上。

所以在这种情况下,我可能会去调整我的自定义服务以至少返回非成功状态,比如 409 Conflict .

如果您仍想返回 200 个成功代码以及真/假响应,您仍然可以使验证器代码不那么难看:

ngModel.$asyncValidators.emailExists = function (modelValue, viewValue) {
    return usersService.emailExists(viewValue).then(function (email_exists) {
        return $q[email_exists ? 'when' : 'reject']();
    });
};

关于javascript - AngularJS : Should service's boolean method return promise that resolves to true/false, 或者被解决/拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703088/

有关javascript - AngularJS : Should service's boolean method return promise that resolves to true/false, 或者被解决/拒绝?的更多相关文章

随机推荐