gpt4 book ai didi

javascript - indexedDB 无法在 "onupgradeneeded"事件上将数据插入数据库

转载 作者:行者123 更新时间:2023-12-03 11:11:44 31 4
gpt4 key购买 nike

我收到的错误是:

Uncaught InvalidStateError: Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction.

这是代码:

    var Database = function ( settings, catalogue ) {

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if ( !window.indexedDB ) {
throw new Error("IndexedDB not supported!");
}

var that = this;
this.settings = settings;
this.catalogue = catalogue;
this.db = null;

var request = indexedDB.open( this.settings.name, this.settings.version );

request.onerror = function ( e ) {
//e.message = "Database initialization error";
console.error( "Database initialization error:", e );
};

request.onsuccess = function ( e ) {

console.log( "Database initialization success" );

// that.db = e.target.result;
// that.db.onerror = function ( e ) {
// console.error( "Database error:", e.target.errorCode );
// };

};

request.onupgradeneeded = function ( e ) {

console.log( "Database upgrade required" );

var db = e.target.result;
db.onerror = function ( e ) {
console.error("Database upgrade error:", e.target.errorCode);
};

that.catalogue.retrieve( function ( catalogue ) {

console.log(catalogue)

var stores = {};

for ( var categoryKey in catalogue ) {

var category = catalogue[categoryKey];

if ( category.length > 0 ) {

var schemaProduct = category[0];

stores[categoryKey] = db.createObjectStore(categoryKey, { keyPath: "id" });

for ( var prop in schemaProduct ) {

stores[categoryKey].createIndex( prop, prop, { unique: false } );

}

stores[categoryKey].transaction.oncomplete = function( e ) {

var transaction = db.transaction(categoryKey, "readwrite").objectStore(categoryKey);

for ( var productKey in category ) {
transaction.add( category[productKey] );
}


console.log("Insertion complete!") // this never fires
}


}

}

});


};



}

var database = new Database( this.options.store.database, new Catalogue( this.options.store.catalogue ) );

我需要一双新的眼睛,因为我似乎无法理解为什么这不起作用,我重写了代码几次,但显然我遗漏了一些东西。

PS:this.catalogue是一个带有ajax请求的对象,它从服务器获取数据。数据正确。

最佳答案

只是猜测,但通常这是因为您同时使用两个不同的异步系统。虽然在有限的情况下这是可能的,但您通常希望避免调用非 indexedDB ajax 函数,例如异步标记的 XMLHttpRequest。一个简单的修复方法是首先调用 Catalogue.retrieve,然后在 Catalogue.retrieve 的回调中使用更高版本调用 indexedDB.open。这样,onupgradeneeded 事务中的语句会在 VERSION_CHANGE 事务处于事件状态时发生。现在看来,在对 Catalogue.retrieve 的调用完成之前,事务就处于事件状态(onupgradeneeded 函数完成并退出)。

换句话说,做:

catalogue.retrieve(function(catalogue) {
var r = indexedDB.open(...);
r.onupgradeneeded = function() {
var db = r.result;
for(var k in catalogue) {
//...
db.createObjectStore(...);
}
};
});

关于javascript - indexedDB 无法在 "onupgradeneeded"事件上将数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552661/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com