我正在尝试编写一个返回使用indexedDB的方法的类(我需要一个可重用的API来与我的其他Web应用程序共享)。
这是我的构造函数到目前为止的样子:
Dim i as Long
For i = 1 to 10
Cells(i,"C").Formula = Cells(i,"A").Value + Cells(i,"B").Value
Next i
然后我在另一个文件(我的商店)中导入客户端:
const IndexDbParams = {
// Update this when changing the db schema
dbVersion: 1,
// Database, object store names
databaseName: "CropViewData",
fieldsObjectStoreName: "fieldsData",
filedObjectStoreKeyName: "key",
zoneMapObjectStoreName: "zoneMapData"
};
class IndexDbClient {
constructor() {
this.initializeDB().then(db => (this.db = db));
}
async initializeDB() {
return new Promise((resolve, reject) => {
const {
dbVersion,
databaseName,
fieldsObjectStoreName,
filedObjectStoreKeyName
} = IndexDbParams;
// Open a connection to indexDB
const DbOpenRequest = window.indexedDB.open(databaseName, dbVersion);
DbOpenRequest.onsuccess = e => {
const db = DbOpenRequest.result;
// Create data stores if none exist
if (db.objectStoreNames.length < 1) {
if (db.objectStoreNames.indexOf(fieldsObjectStoreName) < 0) {
db.createObjectStore(fieldsObjectStoreName, {
keyPath: filedObjectStoreKeyName
});
}
}
// return db object, will come hore from onupgradeneeded as well
resolve(db);
};
// If we need to upgrade db version
DbOpenRequest.onupgradeneeded = e => {
const db = event.target.result;
const objectStore = db.createObjectStore(fieldsObjectStoreName, {
keyPath: filedObjectStoreKeyName
});
};
});
}
getFieldData(compareFunction, queryParams) {
return new Promise((resolve, reject) => {
const { fieldsObjectStoreName } = IndexDbParams;
const transaction = this.db.transaction(
fieldsObjectStoreName,
"readonly"
);
// If db transaction fails, reject
transaction.onerror = e => {
reject(transaction.error);
};
const objectStore = transaction.objectStore(fieldsObjectStoreName);
const cursor = objectStore.openCursor();
// const to store query results
const results = [];
cursor.onsuccess = event => {
const result = cursor.result;
// If we have a entry
if (result) {
// evaluate function here
if (compareFunction(queryParams, result)) {
// Add the entry to the results array
results.push(result.value);
}
// If we have no more entries
} else {
// Return all results
resolve(results);
}
};
cursor.onerror = event => {
reject(cursor.error);
};
});
}
getFieldById(fieldId) {
return new Promise((resolve, reject) => {
this.getFieldData(this.byId, { id: fieldId })
.then(data => {
resolve(data);
})
.catch(e => {
reject(e);
});
});
}
byId({ id }, field) {
return field.id === id;
}
}
export default IndexDbClient;
我收到错误:
未捕获(承诺)TypeError:无法读取属性&#39;事务&#39;的 未定义
如果我从控制台运行相同的功能,则错误不存在。我假设这是由于构造函数没有将db对象分配给IndexDbClient?有没有办法让我解决这个问题 - 我看到它的方式我必须等待import IndexDbClient from "../facades/IndexDbClient";
const db = new IndexDbClient();
db.getFieldById("fe276ead-def3-47a6-aefd-020e844774af").then(res => {
console.log(res);
});
方法中的.onsucess
事件才能确保indexedDB连接是打开的?