0

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.

user1806692
  • 143
  • 1
  • 10
  • 1
    it gets called here `then(f, processErrors);` in `function myGet` – Jaromanda X Nov 30 '16 at 22:50
  • 1
    It requires a knowledge of the use of `.then()` in angular promises. The first parameter to `.then()` is your success callback, which gets invoked if the promise was resolved, and the second parameter is your failure callback which gets invoked if your promise was rejected. So, on the line that @JaromandaX pointed out, it is using `f` as the success callback, which is defined as the return value (a function) of `publishEventMapper()`, which is being passed as an argument into `myGet()` from within the `test()` function. Hope that helps! – mhodges Nov 30 '16 at 22:57

0 Answers0