declaring a promise in angularJS with named success/error callbacks

前端 未结 3 1465
执念已碎
执念已碎 2021-02-02 13:56

I am trying to do something very similar to the $http service. From my understanding $http return a promise object.

When using it the syntax is :

$http(.         


        
3条回答
  •  生来不讨喜
    2021-02-02 14:36

    You need to use the $q service and create and return your own promise in 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);
        });
    

提交回复
热议问题