0

I have an angular app but sometimes my callbacks seem to execute before they should. I have defined an service for my api calls, its methods look like this.

    function addOffer(id) {
        var request = $http({
            method: "get",
            url: "/api/campaign/offers",
            params: {
                action: "add",
                id: id
            }
        });
        return ( request.then(handleSuccess, handleError) );
    }
    function handleError(response) {

        // The API response from the server should be returned in a
        // nomralized format. However, if the request was not handled by the
        // server (or what not handles properly - ex. server error), then we
        // may have to normalize it on our end, as best we can.
        if (
            !angular.isObject(response.data) || !response.data.message
        ) {

            return ( $q.reject("An unknown error occurred.") );

        }

        // Otherwise, use expected error message.
        return ( $q.reject(response.data.message) );

    }

    function handleSuccess(response) {
        return ( response.data );

    }

And then in my controller I have scope functions defined like this

$scope.addOffer = function(){
    campaignService.addOffer($scope.id).then(
        loadRemoteData()
    );
};

The load remote data function syncs the client with what is stored in the application backend.

My problem is that in the controller method addOffer, the loadRemoteData() function fires before the offer is added, so that it loads the data without the new offer. But then upon a forced refresh that offer is there. Is there something that needs to be done differently so that this will work as expected?

1
  • After good amount of research into $q and $http promise implementation, I fell back on my JavaScript basics and answered your question. This again iterates why one's basics must be very strong. Commented Oct 15, 2014 at 18:04

1 Answer 1

2

The problem is with () in loadRemoteData(). No matter where you do this, the loadRemoteData() function will be actually executed. If you just want to pass loadRemoteData function as a success callback to .then() then you should simply pass the name of the function.

Change your controller code to:

$scope.addOffer = function(){
    campaignService.addOffer($scope.id).then(loadRemoteData);
};
Sign up to request clarification or add additional context in comments.

2 Comments

This worked, frustrating that it was such a simple concept of JS. Guess I need to brush up on my JS basics.
Sometimes we miss to see intricate details like these. I do that many times. But as you're saying, fundamentals are all you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.