user3440629
user3440629

Reputation: 198

AngularJS function Execution Issue -- Need to delay execution of second function

I am building small utility to handle shopping cart of user in AngularJS.

Below is my cart-service.js file definition.

var myStoreCartService = angular.module("myStoreCartService", []);

myStoreCartService.factory('Cart', function() {
    var userCart=[];
    var cartSummary=[];

    return{

        addItemToCart: function(item) {
            userCart.push(item);  
        },  

        retrieveCart: function(){
            return userCart;
        },

        getCartSummary: function(){
            cartSummary=[];
            for (var key in userCart){
                var currentItem={"productname":"","price":""};              
                if (userCart.hasOwnProperty(key)){                      
                    currentItem["productname"]=userCart[key].productname;
                    currentItem["price"]=userCart[key].price;
                    cartSummary.push(currentItem);
                    continue;
                };
            }
            return cartSummary;
        },

        getCurrentTotal: function(){
            alert("Sum function called "+ cartSummary);
            var currentSum=0;
                for (var key in cartSummary)
                {  
                    if (cartSummary.hasOwnProperty(key))
                    {    
                        // get sum     
                        currentSum = currentSum+parseInt(cartSummary[key].price);
                        alert(currentSum+" is current sum")
                        continue;
                    };
                }
            return currentSum;
        }

    }

});

Below is method used to update the cart of page.(Defined in controller of page)

function addItemToCartHelper(data){
  Cart.addItemToCart(data);  
  $scope.cart=Cart.retrieveCart();
  $scope.cartLength=$scope.cart.length;
  $scope.userCartSummary=Cart.getCurrentTotal();
  $scope.userCartSummaryFromService=Cart.getCartSummary();
}

My issue is I am not getting correct total sum of the price ,I always get one less item added to my price.

I do realize that, my function to sum the total cost should run only after my cart summary has been updated , but in my case it runs before cart summary update function has been launched.

I need a way to ensure that, cart summary has finished execution before totaling function runs.

Upvotes: 0

Views: 69

Answers (1)

icanbeacoder
icanbeacoder

Reputation: 1388

For the case you mentioned the best approach you can use is the Promise API ($q) service provided by Angularjs. It is used for synchronizing, asynchronous tasks. Like with your case

The Promise API is used to fulfill a promise when a condition is satisfied i.e resolved or rejected.

You can use .then from promise created by deferred object using $q.defer()
Example :

var deferredObject = $q.defer();
var deferredPromise = deferredObject.promise;
deferredPromise.then(successCallback,errorCallback);

deferredObject.resolve() // Calls the successCallback
deferredObject.reject() // Will call errorCallback

For better explanation follow the link - http://andyshora.com/promises-angularjs-explained-as-cartoon.html

Upvotes: 1

Related Questions