鍍金池/ 問答/Linux  數(shù)據(jù)庫  HTML/ 請(qǐng)教一下前端大佬們,使用indexedDB遇到的問題?

請(qǐng)教一下前端大佬們,使用indexedDB遇到的問題?

最近打算把聊天數(shù)據(jù)緩存到本地,開始使用indexedDB,在使用的過程中遇到了些問題,代碼如下

let db;
let chatDB = {
    indexedDB: window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB,
    // 打開數(shù)據(jù)庫
    openDB: function (dbname, version, store) {
        let request = this.indexedDB.open(dbname, version || 1)
        //當(dāng)成功創(chuàng)建數(shù)據(jù)庫時(shí)觸發(fā)
        request.onupgradeneeded = function (event) {
            //數(shù)據(jù)庫對(duì)象
            db = event.target.result;
            //....省略....
        };
        //數(shù)據(jù)庫打開失敗
        request.onerror = function (e) {
            console.log(e.currentTarget.error.message);
        };
        //成功打開數(shù)據(jù)庫
        request.onsuccess = function (e) {
            db = e.target.result;
        };
    },
    //添加數(shù)據(jù)
    addData: function (storeName, data) {
        let store = db.transaction(storeName, 'readwrite').objectStore(storeName)
        let request = store.add(data);
        request.onerror = function () {
            console.error('add添加數(shù)據(jù)庫中已有該數(shù)據(jù)')
        };
        request.onsuccess = function () {
            console.log('add添加數(shù)據(jù)已存入數(shù)據(jù)庫')
        };
    }
}
chatDB.openDB(name,version);
chatDB.addData(db,name,data);

執(zhí)行后報(bào)錯(cuò)如下
clipboard.png

也就是db只在onsuccess之內(nèi)有效

回答
編輯回答
祉小皓

這只是一個(gè)異步流程控制的問題,寫成Promise返回db并使用。而Promise狀態(tài)確定不再更改,也就不會(huì)走你鏈接db的邏輯

2017年11月27日 03:24