Ask the front-end bosses about the problems encountered in using indexedDB?

recently, I intend to cache chat data locally. I encountered some problems in the process of using indexedDB,. The code is as follows

let db;
let chatDB = {
    indexedDB: window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
    // 
    openDB: function (dbname, version, store) {
        let request = this.indexedDB.open(dbname, version || 1)
        //
        request.onupgradeneeded = function (event) {
            //
            db = event.target.result;
            //........
        };
        //
        request.onerror = function (e) {
            console.log(e.currentTarget.error.message);
        };
        //
        request.onsuccess = function (e) {
            db = e.target.result;
        };
    },
    //
    addData: function (storeName, data) {
        let store = db.transaction(storeName, "readwrite").objectStore(storeName)
        let request = store.add(data);
        request.onerror = function () {
            console.error("add")
        };
        request.onsuccess = function () {
            console.log("add")
        };
    }
}
chatDB.openDB(name,version);
chatDB.addData(db,name,data);

the error after execution is as follows
clipboard.png

that is, db is only valid within onsuccess


this is just an asynchronous flow control problem, written as Promise return db and use. And the Promise status is determined not to change, so it won't follow the logic of your link db

.
Menu