2015-04-22 32 views
2

當我插入我的數據庫時,它插入兩次相同的數據。在indexeddb中插入重複值

表創建

var oOptions = { 
    keyPath: account.primaryKey, 
    autoIncrement: true 
}; 
var oStore = dbHandle.createObjectStore(account.tableName, oOptions); 

var oIxOptions = { 
    unique: false 
}; 
account.fields.forEach(function(item) { 
    oStore.createIndex(item + "Index", item, oIxOptions); 
}); 

插入

var defered = $q.defer(); 
try { 
    var objectStore = config.database.transaction(tableName, "readwrite").objectStore(tableName); 
    var result = objectStore.add(entity); 
    result.onerror = function(e) { 
     defered.reject("Can't insert into account"); 
     throw e; 
    } 
    result.onsuccess = function(e) { 
     defered.resolve(); 
    } 
} catch (e) { 
    defered.reject("Can't insert into account"); 
    throw e; 
} 
return defered.promise; 

Retrive

var defered = $q.defer(); 
try { 
    var req = $window.indexedDB.open(config.databaseName, 1.0); 
    req.onsuccess = function(evt) { 
     config.database = evt.target.result; 
     var transaction = config.database.transaction(account.tableName, IDBTransaction.READ_ONLY); 
     var objectStore = transaction.objectStore(account.tableName); 
     var tmpData = []; 
     objectStore.openCursor().onsuccess = function(event) { 
      var cursor = event.target.result; 
      if (!cursor) { 
       defered.resolve(tmpData); 
       return; 
      } 
      tmpData.push(cursor.value); 
      cursor.continue(); 
     }; 
    } 
} catch (e) { 
    defered.reject("Can't pull from account"); 
    throw e; 
} 
return defered.promise; 

任何建議??

+0

您的插入方法被調用兩次,還是隻插入兩次?什麼觸發了對插入方法的調用? – Tom

+0

這與雙重插入無關,但... 您使用try/catch塊包裹在承諾? – tpie

+0

@tpie是的,我不應該在諾言期間使用try ctach嗎? –

回答

1

這可能不是一個indexedDB的問題,更多的是使用try/catch和promise的問題。你有沒有嘗試/抓住和沒有承諾的測試?你在這裏使用承諾的理由是什麼?考慮你不需要try/catch,你不需要承諾來執行這些簡單的任務。

+0

我在IE上測試它..在Ionic IE觸發事件中兩次點擊ng。過濾後的數量觸發我解決了問題。 –