IDBTransaction: commit() 方法
注意:此功能在Web Workers中可用。
commit()
方法是 IDBTransaction
接口的方法,如果在活动事务上调用,则提交事务。
请注意,通常不需要调用commit()
— 当所有未完成的请求都已满足且没有发出新的请求时,事务将自动提交。commit()
可用于启动提交过程,而无需等待来自未完成请求的事件分派。
如果在非活动事务上调用它,则会抛出InvalidStateError
DOMException
。
语法
js
commit()
参数
无。
返回值
无 (undefined
).
异常
InvalidStateError
DOMException
-
如果事务状态不是活动状态,则抛出此异常。
示例
js
const note = document.getElementById("notifications");
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["myDB"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("myObjStore");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
// Force the changes to be committed to the database asap
transaction.commit();
规范
规范 |
---|
Indexed Database API 3.0 # ref-for-dom-idbtransaction-commit② |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。
另请参阅
- 使用 IndexedDB
- 启动事务:
IDBDatabase
- 使用事务:
IDBTransaction
- 设置键范围:
IDBKeyRange
- 检索和更改数据:
IDBObjectStore
- 使用游标:
IDBCursor
- 参考示例:待办事项通知 (查看示例).