Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a promise in angularJS with named success/error callbacks

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(...).success(function(data)) {
   //success callback
}).error(function(data)) {
   //error callback
})

I would like to do just the same but consider my API is GetUserProfile, so I wish to have the syntax :

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

how can I accomplish that using a promise ?

like image 685
Nuno_147 Avatar asked Nov 02 '13 21:11

Nuno_147


People also ask

What does $q do in Angular?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI.

What is Q defer () in AngularJS?

$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.

What is promise in AngularJS?

Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.

What is .then in AngularJS?

The then() function accepts 2 functions as parameters: a function to be executed when the promise is fulfilled, and a function to be executed when the promise is rejected.


2 Answers

The nice thing with open-source is that you can read the source. Here's how the $http service does it:

  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;
  };
like image 135
JB Nizet Avatar answered Oct 04 '22 04:10

JB Nizet


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);
    });
like image 23
katranci Avatar answered Oct 04 '22 04:10

katranci