In angular, why do we need an extra return statement when we are trying to return some data from the custom service

Viewed 258

I am new to javascript and angular .

I have created a custom service in angular which connects to a url and fetches information .I am trying to return reponse.data instead if just response

 var getAlldatas = function($http)
    {
      var getuser= function(username){
     $http.get("https://api.github.com/users/"+username).then(function(response{
                 return response.data;
             });
      };
    };

however this isn't working until I add a return statement right before $https as show below

var getAlldatas = function($http)
{ var getuser= function(username){
     return $http.get("https://api.github.com/users/"+username).then(function(response{
         return response.data;
     });

  };
};

please help me to understand as to why the extra "return" statement is necessary as all i need is to return response.data from this function

2 Answers

You can only ever return from the function you're in.

This means that, when you return response.data, you're only returning from the callback function.

By returning $http.get, you are also returning from your getuser function.

(In this example, $http.get returns a promise, so by returning $http.get, you're returning it's promise. The promise will contain whatever is returned from the callback, so this means you can return a promise containing response.data)

Here getAlldatas & $http.get are to separate functions.$http.get is a method where then handles the callback function.

return response.data; return the response of the request but that request as not yet reached to the function which is calling getAlldatas. The outer return function is used to send that data back to the caller function. Unless the outer return is used , getAlldatas will always return undefined

Related