0

I've heard that $q and promise is great for synchronous programming.

I want my second function to run after my first function which has a timeout. So basically I want mt first function to finish running first before my secondfunction operates

My code is:

<head>
  <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>

<body ng-app="myApp">
  <div ng-controller="myCtrl">
      <button ng-click="myClick()">Click Me!</button>
  </div>
  <script type="text/javascript">
     angular.module('myApp', [])
    .controller('myCtrl',['$scope', '$timeout', '$q', function($scope, $timeout, $q){
    $scope.functionOne = function(){
      return $q(function(resolve, reject){
        $timeout(function(){
          alert("dean");
        }, 3000);
      })
    };
    $scope.functionTwo = function(){
      alert("armada");
    }

    $scope.myClick = function(){
      var promise = $scope.functionOne();
      promise.then(function(){
        $scope.functionTwo();
      }, function(){
        alert("fail");
      })
    };
}]);
  </script>
</body>

Plunker: https://plnkr.co/edit/6hJF4mxrCQ17XXA43eUl?p=preview

Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116

2 Answers2

2

The promise is created but never resolved. But you don't need it at all! $timeout already returns a promise:

$scope.functionOne = function(){
  return $timeout(function(){
    alert("dean");
  }, 3000);
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

The better way for doing what do you want (in my opinion) is:

$scope.functionOne = function(){
  var defer = $q.defer();

  $timeout(function(){
      defer.resolve({data:""}); // or defer.reject(data)
  }, 1000);

  return defer.promise;
};
gianlucatursi
  • 670
  • 5
  • 19