Get value from the variable in the return of the function

1
$scope.fetchData = function (param) {
   var url = param;
   var thumb;
   var imgid = get_numbers(url);
   var hash = ("http://vimeo.com/api/v2/video/" + imgid + ".json");
   $http({
     method: 'GET',
     url: hash
   }).then(function successCallback(response) {
     thumb = response.data[0].thumbnail_medium;
   }, function errorCallback(response) {
      console.log("Request fail");
   });
   return thumb;
};


function get_numbers(input) {
   return input.match(/[0-9]+/g);
}

var imgthumb = $scope.fetchData("http://player.vimeo.com/video/219839519");
alert(imgthumb);

Example: when I make console.log from the variable thumb inside the then function, I can see the value of the variable, but when it returns the main function the value of the variable is undefined.

    
asked by anonymous 16.06.2017 / 18:31

2 answers

1

Stay that way

 $scope.fetchData = function (param) {
                             var defer = $q.defer();
                            var url = param;
                            var thumb;
                            var imgid = get_numbers(url);
                            var hash = ("http://vimeo.com/api/v2/video/" + imgid + ".json");
                            $http({
                                method: 'GET',
                                url: hash

                            }).then(function successCallback(response) {

                                thumb = response.data[0].thumbnail_medium;
                                return  defer.resolve(thumb);

                            }, function errorCallback(response) {
                                return deferred.reject('fail');
                            });

                            return defer.promise;
                        };


                        function get_numbers(input) {
                            return input.match(/[0-9]+/g);
                        }

                        var imgthumb = $scope.fetchData("http://player.vimeo.com/video/219839519");

                        console.log(imgthumb);
    
16.06.2017 / 19:16
0

From what I understand, you're having trouble getting the return on the imgthumb variable, since http.get runs asynchronously. To do this, do the following:

$scope.fetchData = function (param) {
   var url = param;
   var thumb;
   var imgid = get_numbers(url);
   var hash = ("http://vimeo.com/api/v2/video/" + imgid + ".json");
   return $http({
     method: 'GET',
     url: hash
   });
};


function get_numbers(input) {
   return input.match(/[0-9]+/g);
}

$scope.fetchData("http://player.vimeo.com/video/219839519").then(function successCallback(response) {
      alert(response.data[0].thumbnail_medium);
   }, function errorCallback(response) {
      console.log("Request fail");
   });
    
16.06.2017 / 18:47