【问题标题】:Class constructor property value is null类构造函数属性值为 null
【发布时间】:2021-01-20 11:58:41
【问题描述】:

我第一次尝试使用 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() 中为空。我尝试了很多不同的东西,但我显然不明白什么?

【问题讨论】:

  • 哪里是 super(); ? :)
  • @blanknamefornow 我认为 super() 是扩展类中需要的东西?
  • 它不是一个扩展类,所以它没有父构造函数
  • 您期望某些东西现在 可用,而它只会在某些未来 出现。这就是为什么有这些on 事件和监听器的原因。您不能期望将其“展平”以支持某些同步接口。您需要坚持异步性质。因此,不可能调用getObejctStore 并在函数调用返回后立即获得结果。您可以使用 Promise 使异步编程更容易,但它始终保持异步。
  • @Gary 向我们展示你是如何尝试await 的。您的实现可能有问题。

标签: javascript class indexeddb


【解决方案1】:

我使用 Promise 让它工作。

const libraries = new storedLibraries();
libraries.loadLibraries();

类。

class storedLibraries {
    constructor() {
        this.DB_NAME = 'recording-template';
        this.DB_VERSION = 1;
        this.DB_STORE_NAME = 'library';
        this.db = null;
        this.libraries = [];

        if (!('indexedDB' in window)) {
            console.log('This browser doesn\'t support IndexedDB');
            return;
        }
    }
    
    loadLibraries() {
        this.openDb().then((result) => {
            this.getObjectStore().then((result) => {
                for(const res of result) {
                    this.libraries.push(new recordingsTemplate(res));
                }
            });
        }).catch(console.error);
    }

    async openDb() {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var request = indexedDB.open(_self.DB_NAME, _self.DB_VERSION);
            
            request.onsuccess = (event) => {
                console.log("openDb:");
                _self.db = request.result;
                resolve(request.result);
            }
            request.onerror = (event) => {
                console.error("openDb:", event.target.errorCode);
                reject(evt);
            }
            
            request.onupgradeneeded = (event) => {
                console.log("openDb.onupgradeneeded");
                _self.db = request.result;
                var store = event.currentTarget.result.createObjectStore(_self.DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
                var transaction = event.target.transaction;
                
                transaction.oncomplete = (event) => {
                    resolve(store);
                }
            }
        });
        return prom;
    }
    
    async getObjectStore() {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var transaction = _self.db.transaction(["library"], "readwrite");
            var objectStore = transaction.objectStore("library");
            var request = objectStore.getAll();
            
            request.onerror = (event) => {
                // Handle errors!
                reject(event);
            };
            request.onsuccess = (event) => {
                resolve(request.result);
            };
        });
        return prom;
    }
    
    async saveLibrary(template) {
        var _self = this;
        const prom = new Promise((resolve, reject) => {
            var transaction = _self.db.transaction(["library"], "readwrite");
            
            // Do something when all the data is added to the database.
            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
            };
        });
        return prom;
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2010-11-10
    相关资源
    最近更新 更多