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 ?
$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.
$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.
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.
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.
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;
};
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With