Attempting to implement a "nice" feature in AngularJS with my average JS skills, I am seeking feedback on how to enhance or refactor the code below:
angular.module('App').factory("SQLService", function ($q) {
var db = window.openDatabase("FOOD_DATABASE", app.current_version, "FOOD_DATABASE_DN", 5 * 1024 * 1024);
// public methods
function getCategories(){
deferred = $q.defer();
db.transaction(queryDB, errorCB);
function queryDB(tx) {
tx.executeSql('SELECT * FROM CATEGORIES', [], querySelectSuccess, errorCB);
}
return deferred.promise;
}
function getDishes(){
deferred = $q.defer();
db.transaction(queryDB, errorCB);
function queryDB(tx) {
tx.executeSql('SELECT * FROM DISHES', [], querySelectSuccess, errorCB);
}
return deferred.promise;
}
// private-like methods
function errorCB(err) {
alert("Error processing SQL: " + err.code);
}
function querySelectSuccess(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
output_results.push(results.rows.item(i));
}
deferred.resolve(output_results);
}
//expose object with public methods
return {
getCategories: getCategories,
getDishes: getDishes,
};
});
I find creating a global deferred = $q.defer();
in each public function unideal. How can I refactor this to avoid that? Should I declare it as local and figure out how to pass it as an extra parameter to the querySelectSuccess callback? Any thoughts?