【发布时间】:2015-04-22 16:52:06
【问题描述】:
当我在我的数据库中插入时,它会插入两次相同的数据。
表创建
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;
检索
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;
有什么建议吗??
【问题讨论】:
-
您的插入方法是被调用了两次,还是只是插入了两次?是什么触发了对 insert 方法的调用?
-
这与双插入无关,但是...您使用包装在承诺中的 try/catch 块?
-
@tpie 是的,我不应该在 promise 期间使用 try ctach 吗??
-
Promise 允许代码块异步运行,但 try/catch 明显是同步和阻塞的。如果请求在您的尝试块中挂起,您的应用将挂起。