3

I realize this is a very similar question to this one. But I'm still unclear on how to do it in my situation. Just need some help with a successful callback.

This is what works:

function getStuff(accountNumber) {
    var logMessage = 'POST GetStuff';

    return $http.post(GetStuff, { custId: accountNumber })
        .then(log);
}

function log(response) {
    logger.debug(response);
    return response;
}

This is what I want to accomplish:

function getStuff(accountNumber) {
    var logMessage = 'POST GetStuff';

    return $http.post(GetStuff, { custId: accountNumber })
        .then(log(response, logMessage);
}

function log(response, logMessage) {
    logger.debug(logMessage, response);
    return response;
}
Community
  • 1
  • 1
Richard.Davenport
  • 1,453
  • 3
  • 16
  • 31

3 Answers3

8

You can use this:

function getStuff(accountNumber) {
    var logMessage = 'POST GetStuff';

    return $http.post(GetStuff, { custId: accountNumber })
        .then(
           function success(response) {
               return log(response, logMessage);
           }
        );
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
5

Depending on your preference/requirements you could do a few things. I normally write promise callbacks like this, so you could do:

.then(function success(response){
  return log(response, logMessage);
});

or, depending on how you feel about this way (i know some people don't like it, i try to avoid unless absoluley nessesary)

.then(log.bind(null, response, logMessage));

Do either of these work for you?

Shan Robertson
  • 2,742
  • 3
  • 25
  • 43
  • Thanks @Shan, Rohit answered first and the same as your first suggestion, so I took his answer. I couldn't get bind to work and it does look funny, but your first suggestion is good. – Richard.Davenport Sep 08 '15 at 19:11
0

See if it can help you:

function getStuff(accountNumber) {
  var logMessage = 'POST GetStuff';
  var deferred = $q.defer();

  return $http.post(GetStuff, { custId: accountNumber })
   .success(function(response){
      deferred.resolve(response);
      log(response, logMessage);
   }).error(function(){
      deferred.reject();
   })     
   return deferred.promise;
}
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85