Structuring init load with promises is a problem


I was spamming this forum with multiple questions because I could not wrap my head around my problem, which I finally understand I believe.

I must initialize user data from a SQLite database, which I am running through the cordova sqlite plugin. My problem is that reading the DB is in an asynchronous deferrable this.loadData function (below). ( I may be “old fashioned”, but my major complaint here - why can’t DB access be in a synchronous function like all other sane implementations of databases? Without the deferrable it would be straight forward.)

My controller reacts to$stateChangeSuccess where I display aleaflet.js map, that is immediately started by $urlRouterProvider.otherwise('/app/map'); within the state controller.

My problem is that I do not know how to stall the view controller load until all my data is loaded. I tried putting loading the SQLite data into $ionicPlatform.ready so that they would be triggered immediately, but on the device loading the view overtakes the background SQLite thread.

I also tried to load the data within the module during module instantiation by calling this.loadData() at the end. However, the cordova module would not be initialized until then and fail.

What’s the best way? Can I make a custom event that would fire when everything is loaded? Should I add a intermediate view after the splash screen that waits out all progress?

Essentially I have to make the whole app loading procedure wait till my data is loaded and do not know how to handle this when SQLite forces one to make all data access a promise. I really would prefer to have a choice of sync / async DB access somehow.

//this is in a module dataService
this.loadData = function(){
			myDB = $cordovaSQLite.openDB('my.db');
		var deferred = $q.defer();
		myDB.transaction(function(transaction1) {
			transaction1.executeSql('SELECT ID,Data FROM myDB;', [],
					function(tx, result) {
				var dataJSON = result.rows.item(0).Data;
				var dataParsed = JSON.parse(dataJSON);
			function(error) {
				console.log("SELECT failed. Must create table first");
				//do other stuff ... 
		return deferred.promise;

// in my MapViewController the app reacts to 
    $scope.$on("$stateChangeSuccess", function() {
     // init views with the data that should be available now

//this is in the starter module

angular.module('starter',[]).config(function($stateProvider, $urlRouterProvider){
\\... states ...