Skip to content

Instantly share code, notes, and snippets.

@0x00dec0de
Created April 29, 2015 11:23
Show Gist options
  • Save 0x00dec0de/6d82aa641a4024221377 to your computer and use it in GitHub Desktop.
Save 0x00dec0de/6d82aa641a4024221377 to your computer and use it in GitHub Desktop.
// more about the angular promises see on the http://habrahabr.ru/post/221111/ (doc on russian language)
// The promise need be using when a function run as async function.
var app = angular.module('app', []);
app.controller('testController',['$scope','$q',function($scope, $q){
$scope.addOne = function(num){
$scope.step++;
console.log( num );
var q = $q.defer();
if( angular.isNumber(num)){
setTimeout(function(){
q.resolve(num+1)
}, 2000)
}else{
q.reject('NaN')
}
return q.promise;
}
$scope.step = 0;
$scope.myValue = 0;
$scope.promise = $scope.addOne($scope.myValue);
$scope.promise
.then(function(res){
console.log( "This is param:", res );
return $scope.addOne(res)})
.then(function(res){
return $scope.addOne(res)
})
.then(function(res){
console.log("This 'then' do not be running, if errors catched before!");
$scope.myValue = res;
}).finally(function(){
console.log("This is 'finally' method run with any results.");
})
.catch(function(err){
console.log("We catch errors on step:", $scope.step, "Error hendle is:", err);
});
}]);
// for the IE8 "catch" need be uses as
// return doSomethingAsync()["catch"](function(err) {
// return errorHandler(err);
// });
// end for the "IE < 9 ", the "finally" method need be use as a method catch fo the ie8.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment