IDBRequest: transaction 属性
注意:此功能在 Web Workers 中可用。
IDBRequest 接口的只读属性 transaction 返回请求的事务,即该请求是在哪个事务中发出的。
对于不在事务中发出的请求,此属性可能为 null,例如来自 IDBFactory.open 的请求 — 在这种情况下,您只是连接到数据库,没有要返回的事务。如果在打开数据库时需要进行版本升级,那么在 upgradeneeded 事件处理程序期间,transaction 属性将是一个 IDBTransaction,其 mode 等于 "versionchange",可用于访问现有的对象存储和索引,或中止升级。升级完成后,transaction 属性将再次为 null。
值
一个 IDBTransaction 对象。
示例
以下示例请求一个给定的记录标题,在 onsuccess 中从 IDBObjectStore(可在 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① |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。