IDBRequest:transaction 属性

注意:此功能在Web Workers中可用。

transaction 是 IDBRequest 接口的只读属性,它返回请求的事务,即请求在其内部进行的事务。

对于不在事务中进行的请求,此属性可能为 null,例如 IDBFactory.open 返回的请求——在这种情况下,您只是连接到数据库,因此没有事务要返回。如果在打开数据库时需要进行版本升级,则在 upgradeneeded 事件处理程序期间,transaction 属性将为一个 IDBTransaction,其 mode 等于 "versionchange",并且可用于访问现有的对象存储和索引,或中止升级。升级后,transaction 属性将再次为 null

一个 IDBTransaction

示例

以下示例请求给定的记录标题 onsuccessIDBObjectStore(作为 objectStoreTitleRequest.result 提供)获取关联的记录,更新记录的一个属性,然后在另一个请求中将更新后的记录放回对象存储中。请求的源记录到开发者控制台——两者都源自相同的事务。有关完整的示例,请参阅我们的 待办事项通知 应用(查看示例)。

js
const title = "Walk dog";

// Open up a transaction as usual
const objectStore = db
  .transaction(["toDoList"], "readwrite")
  .objectStore("toDoList");

// Get the to-do list object that has this title as its title
const objectStoreTitleRequest = objectStore.get(title);

objectStoreTitleRequest.onsuccess = () => {
  // Grab the data object returned as the result
  const data = objectStoreTitleRequest.result;

  // Update the notified value in the object to "yes"
  data.notified = "yes";

  // Create another request that inserts the item back
  // into the database
  const updateTitleRequest = objectStore.put(data);

  // Log the transaction that originated this request
  console.log(
    `The transaction that originated this request is ${updateTitleRequest.transaction}`,
  );

  // When this new request succeeds, run the displayData()
  // function again to update the display
  updateTitleRequest.onsuccess = () => {
    displayData();
  };
};

此示例演示了如何在版本升级期间使用 transaction 属性访问现有的对象存储

js
const openRequest = indexedDB.open("db", 2);
console.log(openRequest.transaction); // Will log "null".

openRequest.onupgradeneeded = (event) => {
  console.log(openRequest.transaction.mode); // Will log "versionchange".
  const db = openRequest.result;
  if (event.oldVersion < 1) {
    // New database, create "books" object store.
    db.createObjectStore("books");
  }
  if (event.oldVersion < 2) {
    // Upgrading from v1 database: add index on "title" to "books" store.
    const bookStore = openRequest.transaction.objectStore("books");
    bookStore.createIndex("by_title", "title");
  }
};

openRequest.onsuccess = () => {
  console.log(openRequest.transaction); // Will log "null".
};

规范

规范
Indexed Database API 3.0
# ref-for-dom-idbrequest-transaction①

浏览器兼容性

BCD 表仅在启用 JavaScript 的浏览器中加载。

另请参阅