So I have simplified but mimicked this service from a project I am working on at work in an attempt to try and better understand the code that has been written.
The mimicked service below:
angular.module('test').service("giftCardService", ['$http', '$q', function($http, $q) {
function test (callback) {
return myGet('htpp://localhost:7001/getGiftCards/', publishEventMapper());
};
function myGet(url, f) {
return $http.get('http://localhost:7001/getGiftCards/').then(messageHandler).then(f, processErrors);
};
function processErrors(errorResponse) {
console.log('inside processErrors');
return $q(function(resolve, reject) {
reject(processMessages(errorResponse));
});
}
function processMessages(data) {
console.log('inside processMessages');
return {
messages: 'Messages returned'
}
}
function messageHandler(data) {
console.log('inside messageHandler');
return $q(function (resolve) {
console.log('the data', data);
resolve(data);
});
}
function publishEventMapper () {
console.log('publishEventMapper fired');
return function (response) {
mapResponse(response.id);
return [
{
id: 123
}
];
}
};
function mapResponse (items) {
console.log('mapResponse fired');
}
return {
test: test
}
}]);
Just so you are aware...in the real project all code after the test() is actually in another service and in my attempt to learn whats happening I have just recreated it all in one file to make it a bit easier to look through.
Inside the publishEventMapper function it returns a anonymous function that is passed the response which also returns some other object.
My question is:
Where does this anonymous function inside the publishEventMapper get called. I just cant see how it works. Can someone explain it to me like a 3 year old.
Also - does some of this code seem a bit callback hellish? I am looking through a lot of similar stuff that has a function the calls another function that then returns a promise that needs to be resolved and returned. Its making my head spin a bit.