Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Working with callbacks and promises

I am unable to wrap my brain around the concept of asynchronous requests.

I have a controller for my view, which is creating an object instance from a provider:

va.controller('VaCtrl',function($scope,$shipment){
    $scope.shipment = $shipment.Shipment();    
});

The provider:

Shipment.provider('$shipment',function(){

    this.$get = function($http){

        function Shipment(){

        }

        Shipment.prototype.fetchShipment = function(){
            var shipment = undefined;
                $http.post('../sys/core/fetchShipment.php',{
                        // some data to POST
            }).then(function(promise){
                    shipment = promise.data;
                });

            return shipment;
        };

        return {
            Shipment: function(){
                return new Shipment();
            }
        }
    }
});

My goal is to get access to the data from Shipment.prototype.fetchShipment() inside my controller. My approach:

$scope.fetchShipment = function(){
       var shipment = $scope.shipment.fetchShipment();
        console.log(shipment); // undefined
};

However, this will return undefined.

I read about $q, and defers, promises and callbacks, and now i am like WTF; all i want to do is to push the retrieved data to my controller, what is the best possible way to do so?

like image 942
user2422960 Avatar asked Jan 12 '23 20:01

user2422960


1 Answers

You should modify your code as shown below to return the promise from fetchshipment directly, and then use then() inside your controller.

Shipment.prototype.fetchShipment = function(){

    return $http.post('../sys/core/fetchShipment.php',{
        // some data to POST
    })
};


$scope.fetchShipment = function(){
    var shipment = $scope.shipment.fetchShipment().then(function(data){;
        console.log(data);
    });
};

Explanation to Code :

Calling $http return a promise which is resolved when you get the data from the server. In the code above, I have returned $http.post from service function which returns a promise. So in the controller you are waiting for promise to be resolved, and when the promise is resolved, the result is logged to the console.

Read about more promise documentation on angular:

  • http://docs.angularjs.org/api/ng.$q
  • http://docs.angularjs.org/api/ng.$http
like image 56
Ajay Beniwal Avatar answered Jan 21 '23 13:01

Ajay Beniwal