我正在尝试构建一个通用的IndexedDB模块,以便在多个项目中使用。我遇到了一些我无法理解的奇怪行为。
根据我的理解,一个事务只能发生3个事件,但是,当我有目的地应用坏的objectStore时,中止或错误事件都没有执行。
我很困惑是我设置错误还是这是故意的行为,谢谢你花时间研究我的问题!
/**
* Adds a single object to the specificed objectStore
* @param {IDBDatabase} database Initiliazed database
* @param {string} objectStore Name of objectStore where transactions will be occurring
* @param {object} data Object to be inserted into the objectStore
* @returns {Promise} Resolve => String | Reject => Error
*/
async function addRecord(database, storeName, data) {
return new Promise(function (resolve, reject) {
try {
let transaction = database.transaction(storeName, "readwrite");
transaction.oncomplete = function () {
console.log("Add Transaction Successful.");
};
transaction.onabort = function (event) {
throw (`Transaction Aborted - Supplied Data {${database},${storeName},${data}} Code: ${event.target.errorCode} Error: ${request.error}`)
}
transaction.onerror = function (event) {
throw (`Transaction Failed - Supplied Data {${database},${storeName},${data}} Code: ${event.target.errorCode} Error: ${request.error}`)
};
let objectStore = transaction.objectStore(storeName);
let request = objectStore.add(data);
request.onsuccess = function () {
console.log("Add Request Succesful");
resolve()
};
request.onerror = function (event) {
console.log(`Request Failed: addRecord - Supplied Data {${database_name},${database_version},${upgrade_function}} Code: ${event.target.errorCode} Error: ${request.error}`)
throw (`Request Failed: Supplied Data {${database_name},${database_version},${upgrade_function}} Code: ${event.target.errorCode} Error: ${request.error}`)
};
} catch (error) {
reject(`Error: AddRecord - ${error.message}`)
}
});
}
- 在事务完成时而不是在请求完成时解析promise
- 当事务出错时拒绝,而不是当请求出错时拒绝。基本上消除您的请求onsuccess/onerror,或者只使用它们登录控制台,而不使用其他内容
- 不要使用try-catch,catch不会总是捕捉到你期望的错误,它基本上是毫无意义的
- 不要使用async限定符,您没有在等待任何东西,这毫无意义
- 你真的应该退一步去学习异步编程,这是你沮丧的根源,但这不是一个简单的答案,有时需要一本100页的书来解释
根据您的评论,试试这个:
function connect(name, version, onupgradeneeded) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onsuccess = event => resolve(request.result);
request.onerror = event => reject(request.error);
request.onupgradeneeded = onupgradeneeded;
});
}
function addRecord(database, storeName, data) {
return new Promise((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.oncomplete = resolve;
transaction.onerror = event => reject(event.target.error);
transaction.objectStore(storeName).add(data);
});
}
async function main() {
const db = await connect('mydb', 1);
console.log('connected');
try {
await addRecord(db, 'things', { foo: 'bar' });
console.log('added record');
} catch (error) {
console.log(error);
}
}