0
var bar = dataService.makeHttpRequest("GET", "/documents/checkfilename/", null,
            function (data, status, headers, config) {
                // I can see `true` if I alert(data); here
                // I want to return the contents of data because
                // it's a true/false and would perform tasks based
                // on it being true or false.

                return data;
            });

alert(bar); // this should alert `true` or `false` but is `undefined`

Why does alert(bar) always return undefined? I know that data in the above function has true or false, I am able to alert it; but, I want to return it and do things only when it is true.

The dataService.makeHttpRequest service function looks like the following:

dataService.makeHttpRequest = function(requestType, urlString, dataObject, successFunc, errorFunc) {
    $http({
        method:requestType, 
        url:$rootScope.serverAddress+urlString,
        data:dataObject
        })
        .success(successFunc)
        .error(errorFunc);
};
1
  • 1
    The callback you are passing is executed after the HTTP request, so bar is just the return of the function makeHttpRequest which doesn't return anything so you're getting undefined. Commented May 20, 2015 at 20:11

1 Answer 1

1

The simplest explanation for why your method makeHttpRequest is returning undefined is that, well, it doesn't actually return a value (where's the return statement?)

However, even if you were returning the result of the call to $http it wouldn't be what you want. The whole point of a callback is to handle an asynchronous operation -- if you want to perform logic based on data received from the HTTP response, it must be done in the callback itself.

Since $http() returns a promise, a cleaner way to do what you want to do would be:

dataService.makeHttpRequest = function(requestType, urlString, dataObject) {
    return $http({
        method:requestType, 
        url:$rootScope.serverAddress+urlString, //recommend taking this as a parameter instead of abusing $rootScope
        data:dataObject
    });
};

dataService.makeHttpRequest("GET", "/documents/checkfilename/", null).success(function (data, status, headers, config) {
     //do whatever you want with "data" here
}); //can also chain ".error" here to specify an error callback
Sign up to request clarification or add additional context in comments.

1 Comment

yep that's the right answer. although there are cases when you need a $q to time several asynchronous request, even when they are $http

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.