我正在打开一个数据库,然后在其中进行交易。这是代码
var OLC = {}
// Initialising the window.IndexedDB Object
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
var db = null;
OLC.indexedDB = {};
OLC.indexedDB.db = null;
OLC.indexedDB.version = null;
OLC.indexedDB.open = function(type) {
// opening OLCMail DB
try {
var dbOpenRequest = window.indexedDB.open("OLCMail");
dbOpenRequest.onsuccess = function(event){
OLC.indexedDB.db = dbOpenRequest.result;
db = dbOpenRequest.result;
OLC.indexedDB.version = db.version;
var thisDB = db; // Need to create this variable since the variable db is assigned to other things later
db.onversionchange = function(e){
console.log("Version change triggered, so closing database connection", e.oldVersion, e.newVersion, thisDB);
thisDB.close();
};
console.log("Database Opened", db, event);
};
// Creating objectstore "MailHeaders"
dbOpenRequest.onupgradeneeded = function(e){
console.log("Database upgrade needed");
db = dbOpenRequest.result;
var transaction = dbOpenRequest.transaction;
....等等
然后我有一个方法 loadOfflineMails 其目的是创建一个事务并从数据库中获取一个值
OLC.indexedDB.loadOfflineMails = function () {
console.log("Opening a new transaction.");
try {
var db = OLC.indexedDB.db;
console.log(OLC.indexedDB.db);
var objectStore = db.transaction(["MailHeaders"]).objectStore("MailHeaders");
console.log("Object Store opened", objectStore);
var cursor = null;
....很快
我正在运行它
function _init() {
OLC.indexedDB.open();
OLC.indexedDB.loadOfflineMails();
}
window.addEventListener("DOMContentLoaded", _init, false);
我遇到的问题是当 OLC.indexedDB.loadOfflineMails(); 被调用时,OLC.indexedDB 的 db 属性显示为空,因此事务未完成。
但是,当我在 loadOfflineMails() 中的事务语句之前提醒任何值时,代码可以正常工作。前任。
OLC.indexedDB.loadOfflineMails = function () {
console.log("Opening a new transaction.");
try {
alert("ANY THING");
var db = OLC.indexedDB.db;
console.log(OLC.indexedDB.db);
var objectStore = db.transaction(["MailHeaders"]).objectStore("MailHeaders");
console.log("Object Store opened", objectStore);
var cursor = null;
我仍然无法弄清楚警报语句如何导致空 db 属性转换为 IDBDatabase 对象。我试过console.log,延迟代替警报,但没有任何效果,它就像alert()一样会导致奇迹。
仅供参考:我在alert()之前和之后都做了console.log(OLC.indexedDB.db)在alert()之前它是空的,在alert()之后它是一个IDBDatabase对象