Dean Christian Armada Dean Christian Armada - 3 months ago 6
AngularJS Question

Why is the function inside my promise not running

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

Answer

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);
};
Comments