我想用我一般的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();,如果我将其声明为local,则我不知道如何将该延迟对象作为额外参数传递给querySelectSuccess回调。还是我应该以某种方式更好地重构所有内容?你怎么看?

最佳答案

http://rburns.paiges.net/about/回答如下:

function getCategories(){
  return promisedQuery('SELECT * FROM CATEGORIES', defaultResultHandler, defaultErrorHandler);
}

function getDishes(){
  return promisedQuery('SELECT * FROM DISHES', defaultResultHandler, defaultErrorHandler);
}

function defaultResultHandler(deferred) {
  return function(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);
  }
}

function defaultErrorHandler(err) {
  alert("Error processing SQL: " + err.code);
}

function promisedQuery(query, successCB, errorCB) {
  var deferred = $q.defer();
  db.transaction(function(tx){
    tx.executeSql(query, [], successCB(deferred), errorCB);
  }, errorCB);
  return deferred.promise;
}

07-28 03:11