我正在尝试编写一个API来处理我的indexedDB功能。我在将db对象存储到类中时遇到问题,因为我必须等待.open()请求中的.onsuccess
个事件触发。
所以我写了一个初始化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
});
};
});
}
然后我将在所有其他方法的开头调用,例如:
async getData() {
this.initializeDB().then(db => {
// do stuff with the db object
})
}
我的问题是 - 这会浪费比调用.open()
一次,然后将其存储在全局状态更多的资源吗?这种方法的可能后果是什么(如果有的话)?
答案 0 :(得分:0)
绝对不浪费。
我的所有项目都是这样的:
function openDb() {
return new Promise(function(resolve, reject) {
var request = indexedDB.open();
request.onsuccess = () => resolve(request.result);
});
}
function doSomeDbAction() {
openDb().then(function(db) {
// do stuff with db
}).catch(console.warn).finally(function(db) {
if(db) db.close();
});
}
function doAnotherDbAction() {
openDb().then(function(db) {
// do more stuff with db
}).catch(console.warn).finally(function(db) {
if(db) db.close();
});
}