I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been loaded from the server. However, the current setup results in the other commands being executed and displayed in the view before the data is actually retrieved from the server. How can I correct this?
What could be causing the issue in my implementation?
// controller (with $q and KeyGenerationService injected)
$scope.KeyData = null;
var defer = $q.defer();
var promise = defer.promise;
promise
.then(
function() {
var KeyData = {
Server: KeyGenerationService.getKeyDataFromServer()
};
return KeyData;
})
.then(
function(KeyDataFromFunction1) {
var KeyData = {
KeyDateGroup: KeyGenerationService.generateKeyDateGroup(),
KeyID: KeyGenerationService.generateKeyID(),
Server: KeyDataFromFunction1.Server
};
return KeyData;
})
.then(
function(KeyDataFromFunction2){
$scope.KeyData = KeyDataFromFunction2;
})
.catch(
function(error){
window.alert(error);
})
defer.resolve($scope.KeyData)
// factory
.factory('KeyGenerationService', function($q, fbutil) {
// operations
return {
generateKeyDateGroup: function() {
var today = new Date();
var d = today;
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+''+mm+''+ dd;
return today;
},
generateKeyID: function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
},
getKeyDataFromServer: function() {
return fbutil.syncArray('keys');
}
} // return
}) // .factory KeyGenerationService