Richard.Davenport
Richard.Davenport

Reputation: 1501

Passing parameters to promise's success callback in angularjs $q

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;
}

Upvotes: 3

Views: 14276

Answers (3)

Ali Adravi
Ali Adravi

Reputation: 22733

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;
}

Upvotes: 0

Shan Robertson
Shan Robertson

Reputation: 2742

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?

Upvotes: 5

Rohit Jain
Rohit Jain

Reputation: 213263

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);
           }
        );
}

Upvotes: 9

Related Questions