Search code examples
angularjsfunctionhttpresponse

AngularJS wait for external function response to continue


I have this function on my controller:

   // Get a specific Parte
    partesc.getParte = function (id) {
            var url = endpointApiURL.url + "/fabricante/" + id;
            $scope.PartesPromise = $http.get(url)
                .then(function (response) {
                    partesc.parte= response.data;
                })
                .catch(function (error) {
                    console.log(error);
                    if (error.status == '412') {
                        console.log('Error obteniendo datos: ' + error.data.error);
                    }
                });
        }

And i have this second function:

partesc.openEdit = function(id) {
partesc.getParte(id);
    console.log(partesc.parte); }

I call openEdit function from a button on the front end. So the console.log part prints undefined. I think that is not waiting for the response of the calling the function getParte(id).

How i can make that wait for the response of the function to print the result? i'm doing this on the wrong way?

UPDATE 1

The console.log is just for reference. I need use the data that return the another function (getParte) inside the another one (openEdit)

SOLUTION

I find the solution thanks to the answer that i accepted here.

        // Get a specific Parte
    partesc.getParte = function (id) {
            var url = endpointApiURL.url + "/fabricante/" + id;
             return $http.get(url)
                .then(function (response) {
                    partesc.parte= response.data;
                })
                .catch(function (error) {
                    console.log(error);
                    if (error.status == '412') {
                        console.log('Error obteniendo datos: ' + error.data.error);
                    }
                });
        }


partesc.openEdit = function(id) {
    $scope.PartesPromise = partesc.getParte(id)
                            .then(function() {
                                console.log(partesc.parte);
                                }); 
}

Thanks


Solution

  • Then if you can return the promise:

     partesc.getParte = function (id) {
         var url = endpointApiURL.url + "/fabricante/" + id;
         return $http.get(url);
     };
    
    partesc.openEdit = function(id) {
        partesc.getParte(id).then(function(response){
        // stuff you want to do
        });
    };