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

Nun*_*147 17 javascript promise angularjs

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

使用时,语法为:

$http(...).success(function(data)) {
   //success callback
}).error(function(data)) {
   //error callback
})
Run Code Online (Sandbox Code Playgroud)

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

GetUserProfile(...).success(function(data) {
   // success callback
}).error(function(data)) {
   // error callback
})
Run Code Online (Sandbox Code Playgroud)

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

JB *_*zet 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;
  };
Run Code Online (Sandbox Code Playgroud)

  • 我想知道为什么角度中的原生$ q没有这个. (3认同)

kat*_*nci 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);
    });
Run Code Online (Sandbox Code Playgroud)


Eri*_*hen 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;
});
Run Code Online (Sandbox Code Playgroud)