如何检查indexedDB实例是否打开? [英] How do I check if an indexedDB instance is open?

查看:129
本文介绍了如何检查indexedDB实例是否打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个indexedDB对象的实例.是否有一种简单的方法来检测对象当前是否处于打开"状态?

Suppose I have an instance of an indexedDB object. Is there a simple way of detecting if the object is currently in the 'open' state?

我尝试了database.closePending并查看了其他属性,但没有看到一个简单的属性来告诉我数据库的状态.

I've tried database.closePending and looking at other properties but do not see a simple property that tells me the state of the database.

  • 我正在寻找同步的方法.
  • 做诸如尝试在数据库上打开事务并检查是否发生异常之类的事情对我来说不是一个合理的解决方案.
  • 我不想维护与数据库实例相关联的额外变量.

也许我在api中缺少一些简单的功能?实例变量是否有一些可观察的功能,我可以快速轻松地查询以确定状态?

Perhaps I am missing some simple function in the api? Is there some observable feature of the instance variable that I can quickly and easily query to determine state?

以另一种方式表示,您可以改进以下实现吗?

Stated a different way, can you improve upon the following implementation?

function isOpen(db) {
  if(db && Object.prototype.toString.call(db) === '[object IDBDatabase]') {
    var names = db.objectStoreNames();
    if(names && names.length) {
      try {
        var transaction = db.transaction(names[0]);
        transaction.abort();
        return true;
      } catch(error) {
      }
    }
  }
}

还是这种方法?

var opened = false;
var db;
var request = indexedDB.open(...);
request.onsuccess = function() {
  db = request.result;
  opened = true;
};

function isOpen(db) {
  return opened;
}

db.close();
opened = false;

还是这种方法?

var db;
var request = indexedDB.open(...);
request.onsuccess = function() {
  db = request.result;
  db.onclose = function() {
    db._secret_did_close = true;
  };
};

function isOpen(db) {
  return db instanceof IDBDatabase && !db.hasOwnProperty('_secret_did_close');
}

推荐答案

API中没有其他内容可以告诉您连接是否关闭.您所列举的可能性就是可用的.

There's nothing else in the API that tells you if a connection is closed. Your enumeration of possibilities is what is available.

还请注意,API中没有closePending属性.规范文本使用关闭未决标志来表示内部状态,但这未在脚本中公开.

Also note that there is no closePending property in the API. The specification text uses a close pending flag to represent internal state, but this is not exposed to script.

做诸如尝试在数据库上打开事务并检查是否发生异常之类的事情对我来说不是一个合理的解决方案.

Doing something like attempting open a transaction on a database and checking if an exception occurs is not a reasonable solution for me.

为什么?这是最可靠的方法.维持额外的状态不会考虑到意外关闭(例如,用户已删除浏览数据,迫使连接关闭),尽管这是onclose处理程序要考虑的问题-您需要结合第二种和第三种方法. (如果脚本调用close(),则不会触发close)

Why? This is the most reliable approach. Maintaining extra state would not account for unexpected closure (e.g. the user has deleted browsing data, forcing the connection to close) although that's what the onclose handler would account for - you'd need to combine your 2nd and 3rd approaches. (close is not fired if close() is called by script)

这篇关于如何检查indexedDB实例是否打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆