saurav
saurav

Reputation: 219

Angular: How to make one async function executes first after another

I have a save function where i need to call another function to get revision num. and there am making api call. since both are async in nature . How to make one function to make wait until other executes

$scope.getRevision = function(callback){
    Api.Product.querymyProdById({ prodId: $scope.editProdId }).$promise.then(function(result) {
        if (result && result.length>=1 && result[0].effectiveDate != $scope.editProdmyDate) {
            $scope.editProdRevision = result && result[0].revision +1;
            callback();
        } else {
            $scope.editProdRevision = 100;
        }
    });
}

$scope.saveProd = function(){
     $scope.getRevision(function(){});

     Api.Product.save({
        id: $scope.ProdId;
        revision:$scope.editProdRevision
         -some code

}

The above code i wanted to make sure save api should not get called until i get the prodRevision.

Any suggestion?

Upvotes: 1

Views: 1017

Answers (3)

atefth
atefth

Reputation: 1623

You could simple make one async call after the other, like this -

// First Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
})
.then(function successCallback(response) {
  // this callback will be called asynchronously
  // when the response is available
  // Second Simple GET request example:
   $http({
     method: 'GET',
     url: '/someUrl'
   })
   .then(function successCallback(response) {

   }, function errorCallback(response) {

   });
}, function errorCallback(response) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Since you have promises do not mess with callbacks. Make your functions actually return a promise and use then to chain calls.

$scope.getRevision = function(){
    return Api.Product.querymyProdById(..).$promise...;
}

$scope.saveProd = function() {
   return $scope.getRevision().then(function() {
        return Api.Product.save(...);
   })
}

Upvotes: 5

devnull69
devnull69

Reputation: 16574

That's exactly what javascript gods invented callbacks for

$scope.saveProd = function(){
     $scope.getRevision(function(){
        // this happens after getRevision finished
        Api.Product.save({
           id: $scope.ProdId;
           revision:$scope.editProdRevision
            -saome code
        });
     });

}

Upvotes: 1

Related Questions