我第一次尝试使用indexedDB,并想为它创建一个类。我的代码可以打开数据库并将对象保存到其中,但当我尝试检索对象时,它为空
var libraries = new storedLibraries();
libraries.openDb();
user action
libraries.saveLibrary(template);
上课。
class storedLibraries {
constructor() {
this.DB_NAME = 'recording-template';
this.DB_VERSION = 1;
this.DB_STORE_NAME = 'library';
this.db = null;
this.result = null;
if (!('indexedDB' in window)) {
console.log('This browser doesn\'t support IndexedDB');
return;
}
}
openDb() {
var request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
var _self = this;
request.onsuccess = function (evt) {
_self.db = this.result;
_self.getObjectStore();
console.log(_self.result);
console.log("openDb DONE");
};
request.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
request.onupgradeneeded = function (evt) {
console.log("openDb.onupgradeneeded");
var store = evt.currentTarget.result.createObjectStore(_self.DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
};
}
saveLibrary(template) {
var transaction = this.db.transaction(["library"], "readwrite");
// Do something when all the data is added to the database.
var _self = this;
transaction.oncomplete = function(event) {
console.log("All done!");
};
transaction.onerror = function(event) {
// Don't forget to handle errors!
};
var objectStore = transaction.objectStore("library");
var request = objectStore.add(template);
request.onsuccess = function(event) {
// event.target.result
};
}
getObjectStore() {
//console.log(this);
var transaction = this.db.transaction(["library"], "readwrite");
var objectStore = transaction.objectStore("library");
var request = objectStore.getAll();
var _self = this;
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
_self.result = request.result;
console.log(_self.result);
};
}
}
getObjectStore()中的console.log(_self.result);
输出了正确的值,但在openDb()中它是空的。我尝试了许多不同的方法,但我显然不明白什么?
1条答案
按热度按时间ao218c7q1#
我用承诺让它起作用了。
上课。