每笔交易都在调用 window.indexedDB.open() 浪费

is calling window.indexedDB.open() with every transaction wasteful

我正在尝试编写 API 来处理我的 indexedDB 功能。我无法将 db 对象存储在 class 中,因为我必须等待 .open() 请求中的 .onsuccess 事件触发。

所以我写了一个初始化数据库的方法:

async initializeDB() {
    return new Promise((resolve, reject) => {
      const {
        dbVersion,
        databaseName,
        fieldsObjectStoreName,
        filedObjectStoreKeyName
      } = IndexDbParams;
      // Open a connection to indexDB
      const DbOpenRequest = window.indexedDB.open(databaseName, dbVersion);
      DbOpenRequest.onsuccess = e => {
        const db = DbOpenRequest.result;
        // Create data stores if none exist
        if (db.objectStoreNames.length < 1) {
          if (db.objectStoreNames.indexOf(fieldsObjectStoreName) < 0) {
            db.createObjectStore(fieldsObjectStoreName, {
              keyPath: filedObjectStoreKeyName
            });
          }
        }
        // return db object, will come hore from onupgradeneeded as well
        resolve(db);
      };
      // If we need to upgrade db version
      DbOpenRequest.onupgradeneeded = e => {
        const db = event.target.result;
        const objectStore = db.createObjectStore(fieldsObjectStoreName, {
          keyPath: filedObjectStoreKeyName
        });
      };
    });
  }

然后我会在所有其他方法的开头调用它,例如:

async getData() {
   this.initializeDB().then(db => {
     // do stuff with the db object
   })
}

我的问题是 - 这是否比调用 .open() 一次,然后将其存储在全局状态中浪费更多的资源?这种方法的可能后果是什么(如果有的话)?

绝对不浪费

我所有的项目都是这样的:

function openDb() {
  return new Promise(function(resolve, reject) {
    var request = indexedDB.open();
    request.onsuccess = () => resolve(request.result);
  });
}

function doSomeDbAction() {
  openDb().then(function(db) {
     // do stuff with db
  }).catch(console.warn).finally(function(db) {
    if(db) db.close();
  });
}

function doAnotherDbAction() {
  openDb().then(function(db) {
     // do more stuff with db
  }).catch(console.warn).finally(function(db) {
    if(db) db.close();
  });
}