2011-05-16 30 views
1

我想做一個簡單的WebOS魔的應用,增加了日期的數據庫,但在此之前,它需要通過查詢數據庫來檢查幾個條件。由於訪問數據庫中的WebOS我想知道什麼是寫這樣的代碼的最有效和最一小段路的異步模式。如何組織依賴於以前的結果WebOS的SQL代碼?

比如我需要確保新日期尚未在數據庫中。然後我需要得到最近的日期,以便我可以計算天數的差異,並在差異太小時拋出錯誤。然後我需要插入新的日期,然後計算一個平均值。

這會很容易在訪問數據庫的同步方式做,但我真的不喜歡在執行不同的SQL語句的多個成功處理程序編寫代碼的部分的想法。有沒有更優雅的解決方案?

回答

1

您可以使用內聯回調到HTML 5的關係數據庫功能:

function createProject(project, onSuccess) { 
if (project.projectId) 
    throw new StorageError("project already exists"); 
if (project.path) 
    throw new StorageError("project already has a path"); 

project.projectId = ++Tracker.maxLocalId * 4096; 
project.path = calcNextProjectPath(); 
project.normalize(); 

Tracker.db.transaction(
    function (transaction) { 
     transaction.executeSql(
      "INSERT OR ROLLBACK INTO item (dbId, path, hasChildren, kind, summaryText, place, work, responsible, responsibleClass) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", 
      [project.projectId, project.path, project.hasChildren, project.kind, project.title, project.place, project.work, project.responsible, project.responsibleClass], 

      function (transaction, resultSet) { 
       Mojo.Log.info("DB: inserted new project item", resultSet.insertId, project.title); 

       transaction.executeSql(
        "INSERT OR ROLLBACK INTO project (projectId, accountId, title, backendKind, backendStatus, backendLastChanged, lastSuccessfulDown) \ 
          VALUES (?, ?, ?, ?, ?, ?, ?)", 
        [project.projectId, project.accountId, project.title, project.backendKind, project.backendStatus, project.backendLastChanged, project.lastSuccessfulDown], 

        function (transaction, resultSet) { 
         Warn.logInfo("created new project", "projectId=" + resultSet.insertId, project.title); 
         if (onSuccess) 
          onSuccess(); 
        }, 

        function (transaction, sqlError) { 
         Warn.bannerError("create", $L("Quit and reset your phone."), "project row insertion failed: ", sqlError.message, sqlError.code, project); 
         return true; // abort whole transaction 
        } 
       ); 
      }, 

      function (transaction, sqlError) { // failure of insert project item 
       if (sqlError.code === 1 && sqlError.message === "constraint failed" && Mojo.appInfo.id !== "com.outlinetracker.outlinetracker") { 
        upgradeAlert(true); 
       } else { 
        Warn.bannerError("create", $L("Quit and reset your phone."), "project item insertion failed: ", sqlError.message, sqlError.code); 
       } 
       return true; // abort whole transaction 
      } 
     );     
    }, // end transaction function 

    function (sqlError) { // seems to only be called for exceptions in callbacks 
     Warn.logError($L("Quit and reset your phone."), "transaction 'insert project' failed", sqlError.message, sqlError.code); 
    } 
); // end transaction call 

}

+0

沒錯,它的確看起來這是工作的唯一途徑。我想不出別的東西。我不喜歡太多的縮進級別,但我必須得到使用:) – rslite 2011-06-28 23:21:42