I have a SQLService running on my PhoneGap/AngularJS app that processes a long array of Guidelines with DB transactions. How can I indicate when the final transaction is completed?
I envision a flow like this:
In the controller, call `SQLService.ParseJSON`
ParseJSON triggers `generateIntersectionSnippets`
`generateIntersectionSnippets` makes multiple calls to `getKeywordInCategory``
Trigger `.then` when the final call to getKeywordInCategory is completed
SQLService.ParseJSON is finished, fire `.then`
I am struggling to manage the asynchronous calls. ParseJSON
returns a promise resolved when generateIntersectionSnippets()
finishes, but generateIntersectionSnippets()
makes multiple calls to getKeywordInCategory
, each returning promises.
Here is a simplified version of the issue:
I aim for $scope.ready = 2
to execute after all transactions are done. Currently, it executes after one iteration through generateIntersectionSnippets
.
In the controller:
SQLService.parseJSON().then(function(d) {
console.log("finished parsing JSON")
$scope.ready = 2;
});
Service:
.factory('SQLService', ['$q',
function ($q) {
function parseJSON() {
var deferred = $q.defer();
function generateIntersectionSnippets(guideline, index) {
var snippet_self, snippet_other;
for (var i = 0; i < guideline.intersections.length; i++) {
snippet_self = getKeywordInCategory(guideline.line_id, snippets.keyword).then(function() {
//Should something go here?
});
snippet_other = getKeywordInCategory(guideline.intersections[i].line_id, snippets.keyword).then(function() {
//Should something go here?
});
}
}
deferred.resolve(); //Is fired before the transactions above are complete
}
generateIntersectionSnippets();
return deferred.promise;
} //End ParseJSON
function getKeywordInCategory(keyword, category) {
var deferred = $q.defer();
var query = "SELECT category, id, chapter, header, snippet(guidelines, '<b>', '</b>', '...', '-1', '-24' ) AS snip FROM guidelines WHERE content MATCH '" + keyword + "' AND id='" + category + "';",
results = [];
db.transaction(function(transaction) {
transaction.executeSql(query, [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
results.push(row);
}
}
},defaultErrorHandler);
deferred.resolve(responses);
},defaultErrorHandler,defaultNullHandler);
return deferred.promise;
}
return {
parseJSON : parseJSON
};
}]);
I am seeking guidance on the correct approach for chaining promises across multiple asynchronous transactions. The current structure is flawed, and any assistance is appreciated.