AngularJS :服务的布尔方法 return 应该承诺解析为 true/false,还是得到 resolved/rejected?

AngularJS : Should service's boolean method return promise that resolves to true/false, or that gets resolved/rejected?

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

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

让方法 emailExists(email) 到 return 承诺在正常操作中解析为 truefalse 对我来说感觉很自然。如果只有我们有一些意外的错误(比如,服务器 returned 500: internal server error,那么 promise 应该被拒绝,但在正常操作中,它被解析为相应的布尔值。

然而,当我开始实施我的异步验证程序指令时(通过 $asyncValidators),我看到它需要 resolved/rejected 承诺。所以,到现在为止,我得到了这个相当难看的代码:

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

})();

这让我觉得我应该修改我的服务,以便 return 改为 resolved/rejected 承诺。但是,这对我来说感觉有点不自然:在我看来,拒绝承诺意味着“我们无法得到结果”,而不是“负面结果[=40=” ]".

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

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

感谢任何帮助。

在这种情况下,没有 correct/incorrect 解决此问题的方法。你说的查邮件服务挺有道理的:其实数据库里存在邮件严格来说不代表失败场景,promise rejection通常对应和反映。

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

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

如果您仍然想要 return 200 个成功代码以及 true/false 共鸣,您仍然可以使验证器代码不那么难看:

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