IDBTransaction: commit() 方法
注意:此功能在 Web Workers 中可用。
commit() 方法是 IDBTransaction 接口的一个方法,如果在一个活跃的事务上调用,则会提交该事务。
请注意,通常不必显式调用 commit() —— 当所有挂起的请求都已满足且没有新的请求被发出时,事务将自动提交。commit() 可用于启动提交过程,而无需等待挂起请求的事件被分派。
如果在非活跃事务上调用该方法,则会抛出一个 InvalidStateError DOMException。
语法
js
commit()
参数
无。
返回值
无(undefined)。
异常
InvalidStateErrorDOMException-
如果事务状态不是活跃状态,则抛出此异常。
示例
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② |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。