AngularJS实现$q

AngularJS实现$q,angularjs,angular-promise,Angularjs,Angular Promise,在返回之前,我如何实现$q来解析承诺?虽然http确实返回了承诺,但您可以像处理结果一样使用$q库: ( function() { angular.module('foo') .factory('someFac', function ($injector, $http, $q){ var temp; $http.get('url').then(function(response){ //implement $q to wait for this to finis

在返回之前,我如何实现$q来解析承诺?

虽然http确实返回了承诺,但您可以像处理结果一样使用$q库:

( function() {
  angular.module('foo')

  .factory('someFac', function ($injector, $http, $q){
      var temp;
      $http.get('url').then(function(response){ //implement $q to wait for this to finish
           if(response === 1){
               temp = 1
           else{
               temp = 2
      });
     return $injector.get(temp); 
}());

您可以拒绝或解析并通过defer对象传递必要的数据。

您将此代码添加到app.js文件中,不需要从服务器端抛出异常,只需在异常中添加代码,就像

( function() {
angular.module('foo')

  .factory('someFac', function ($injector, $http, $q){
    var temp;
    var deferred = $q.defer();
    $http.get('url').then(function(response){ //implement $q to wait for this to finish
       if(response === 1){
           deferred.resolve(1);
       else{
           deferred.reject(2);
  });
 return deferred.promise; 
}());
它会自动捕获$q服务,您可以在服务器代码中添加所需的错误代码,并在交换机中映射到此处

public ActionResult YourMethodName(string emailAddress)
    {
        BasicResponse Response = new BasicResponse();

        try
        {
           // do your work here
        }
        catch (Exception ex)
        {
            Response.ErrorKey = ex.Message;
            Response.ErrorCode = (int)HttpStatusCode.BadRequest;
        }

        return Json(Response, JsonRequestBehavior.AllowGet);
    }

这里不需要
$q
,因为
$http
已经返回了一个承诺,但是在这种情况下,您的代码位于
then
块中,这意味着它已经在等待调用完成。您遇到的真正问题是什么?假设程序使用$http.get从URL获取信息,但它在承诺完成之前返回,导致错误,我无法编辑从何处调用它,因为它是直接从AngularJS代码调用的。只需根据此代码似乎要做的事情在这里进行猜测,您的
返回就不会等待承诺完成,因为承诺的全部目的是允许执行继续。您可能希望将返回放入
然后
回调中。您不能等待。忘记等待吧。您可以做的是返回$http承诺,然后在调用代码中调用then()。阅读我认为您的代码流表明您误解了承诺的工作方式。在将值分配给
temp
之前,您已经在等待承诺完成,但您正在尝试立即进行另一个依赖该值的调用。这与问题有什么关系?这是为了一个不同的问题吗?这个问题与异常无关,甚至与此代码无关。我明白你的意思,是的,这个问题与异常无关,但你也可以通过$q管理异常。所以你说这仍然是一个好答案,因为它使用了问题提到的库,虽然它没有说明OP想要做什么?事实上,提到在服务器端做一些事情,服务器代码可能是OP使用的语言,也可能不是?
angular.module('foo').factory('responeInterceptor', ['$q', '$window', '$injector', 'NotificationService', function ($q, $window, $injector, notifyService) {
    return {
        'response': function (response) {
            // do something on success
            return response;
        },

        //in case of Error
        'responseError': function (rejection) {


            switch (rejection.status) {
                case 400:
                    notifyService.notifyError(rejection.data.errorKey);
                    break;
                case 403:
                    $window.location.href = '/Logout';
                    break;
                default:
            }
            return $q.reject(rejection);
        }
    };
}]);