i'm using angularjs application. have form. on submit i'm calling function. have used javascript try/catch/finally block
$scope.save = function() { try { //block of code try $scope.submit.text = "submitting"; $scope.submit.disable = true; $timeout(function(){ alert('successfully saved'); }, 5000); } catch(err) { //block of code handle errors } { alert("finally"); $scope.submit.text = "submit"; $scope.submit.disable = false; } } i used timer now. later may use ajax call. problem is
finally block gets executed before time finishes. how solve this?
the reason why method gets executed before time finished javascript methods not running asynchronous. promises solve problem.
here how promise defined in q.js used in angular:
a promise object represents return value or thrown exception function may provide. promise can used proxy remote object overcome latency.
one of guarantees promises make either success or error callback invoked, never both. happens if need ensure specific function executes regardless of result of promise? can registering function on promise using finally() method.
suppose have function getdata() making $http request , obtain data backend. can use:
var promise = getdata() .then(function(data) { console.log(data) }, function(error) { console.error(error) }) .finally(function() { console.log() }) })
Comments
Post a Comment