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

14,035

Solution 1

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

Solution 2

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?

Share:
14,035
Richard.Davenport
Author by

Richard.Davenport

ASP.NET C#, HTML, CSS, Javascript

Updated on August 25, 2022

Comments

  • Richard.Davenport
    Richard.Davenport over 1 year

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