取消阻止IndexedDB

时间:2017-01-09 14:13:28

标签: javascript indexeddb

尝试使用IndexedDB。我写了一个函数来创建新的表和索引,并带回回调。

但是当我尝试使用该功能时,它会停止工作 - 在onsuccess状态之后我获得了onblocked状态而onupgradeneeded没有运行...

如何避免阻止DB?

crtTable(db_name, table, indexes, callback) {
    console.log("Initiate table creation");
    let isSupport:boolean = this.checkDbSupport();
    if(!isSupport) return;

    let version;
    let openRequest = indexedDB.open(db_name);
    openRequest.onsuccess = (event) => {
        console.log("Opening DB and find version");
        version = (event.target as any).result.version;

        //I GOT DB VERSION AND NOW I TRYING TO CLOSE IT!
        (event.target as any).result.close();

        version++;

        console.log("reopen DB with new version")
        let openRequest = indexedDB.open(db_name, version);

        openRequest.onblocked = (event) => {
            console.log("blocked");
        }

        openRequest.onupgradeneeded = (event) => {
            console.log("update running")
            let db = (event.target as any).result;

            let transaction = db.createObjectStore(table[0], { keyPath: table[1] });
            for(let index of indexes) {
                transaction.createIndex(index[0], index[0], { unique: index[1] });
            }
            transaction.oncomplete = (event) => {
                console.log("indexes setted");
            }
            callback("updated");
            console.log("updated");
        };

        openRequest.onsuccess = (event) => {
            openRequest.result.close();
            callback("success");
            console.log("success");
        };

        openRequest.onerror = (event) => {
            openRequest.result.close();
            callback("error");
            console.log("error");
        };
    };
}

1 个答案:

答案 0 :(得分:1)

在将数据库升级到新版本之前,必须先关闭其他数据库连接。

  

IDBOpenDBRequest.onblocked事件处理程序是被阻止事件的事件处理程序。当由于版本更改而触发upgradeneeded时会触发此事件,但即使在发送版本更改事件之后,数据库仍在某处使用(即未关闭)。

https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onblocked

<强>更新

您正尝试在onsuccessonerror事件上关闭它并且由于数据库已经打开而没有调用它,并且它调用onblocked事件尝试关闭{{1上的数据库也是事件。

onblocked