我正在尝试用我一般的 JS 技能在 AngularJS 中做一些“好”的事情,我想听听您的感受或改进/重构以下内容:
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;
}
// something like private 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,
};
});
我不喜欢的第一件事是deferred = $q.defer();
在每个公共函数中创建全局,如果我将其声明为本地,那么我不知道如何将该延迟对象作为额外参数传递给 querySelectSuccess 回调。还是我应该以某种方式更好地重构所有内容?你怎么看?