使用命名的成功/错误回调在angularJS中声明一个promise

时间:2013-11-02 21:13:03

标签: javascript angularjs promise

我正在尝试做一些与$ http服务非常相似的事情。从我的理解$ http返回一个promise对象。

使用时,语法为:

$http(...).success(function(data)) {
   //success callback
}).error(function(data)) {
   //error callback
})

我想做同样的事情,但我认为我的API是GetUserProfile,所以我希望有这样的语法:

GetUserProfile(...).success(function(data) {
   // success callback
}).error(function(data)) {
   // error callback
})

如何使用承诺实现这一目标?

3 个答案:

答案 0 :(得分:27)

开源的好处是你可以阅读源代码。以下是$ http服务的用途:

  promise.success = function(fn) {
    promise.then(function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

  promise.error = function(fn) {
    promise.then(null, function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

答案 1 :(得分:9)

您需要使用$ q服务并在GetUserProfile中创建并返回您自己的承诺:

function GetUserProfile() {
    var deferred = $q.defer();
    var promise = deferred.promise;

    // success condition
    if (!true) {
        deferred.resolve('data');
    // error condition
    } else {
        deferred.reject('error');
    }

    promise.success = function(fn) {
        promise.then(fn);
        return promise;
    }

    promise.error = function(fn) {
        promise.then(null, fn);
        return promise;
    }

    return promise;
}

GetUserProfile()
    .success(function(data) {
        console.log(data);
    })
    .error(function(error) {
        console.error(error);
    });

答案 2 :(得分:9)

您不需要更改源代码。 Angular提供了一种更改角度的任何服务的方法,包括$ q。

$ provide.decorator非常适合您的要求 这是我的代码。

将它放在app.module('...')。config

$provide.decorator('$q', function($delegate) {
  function httpResponseWrapper(fn) {
    return function(res) {
      if (res.hasOwnProperty('data') && res.hasOwnProperty('status') && res.hasOwnProperty('headers') && res.hasOwnProperty('config') && res.hasOwnProperty('statusText')) {
        return fn(res.data, res.status, res.headers, res.config, res.statusText);
      } else {
        return fn(res);
      }
    };
  };
  function decorator(promise) {
    promise.success = function(fn) {
      return decorator(promise.then(httpResponseWrapper(fn)));
    };
    promise.error = function(fn) {
      return decorator(promise.then(null, httpResponseWrapper(fn)));
    };
    return promise;
  };
  var defer = $delegate.defer;
  $delegate.defer = function() {
    var deferred = defer();
    decorator(deferred.promise);
    return deferred;
  };
  return $delegate;
});
相关问题