非同期処理を記述するための優れたパターンがプロミスです。AngularJS における実装ではこちらの公式ページで紹介されている $q
を利用します。
<!DOCTYPE html>
<html lang="ja" ng-app="myApp">
<head>
<meta charset="utf-8">
<script src="angular.min.js"></script>
</head>
<body>
<div ng-controller="myController"></div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$timeout', '$q', function($scope, $timeout, $q){
function async() {
var deferred = $q.defer();
$timeout(function(){
deferred.notify('START');
if(true) {
deferred.resolve('OK');
}
else {
deferred.reject('NOT OK');
}
}, 1000); //msec
return deferred.promise;
}
var promise = async();
promise.then(function(msg){
console.log('resolved, ' + msg);
}, function(msg){
console.log('rejected, ' + msg);
}, function(msg){
console.log('notified, ' + msg);
}).finally(function(){
console.log('finalize');
});
}]);
</script>
</body>
</html>