IDBTransaction: phương thức commit()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2021.
Note: This feature is available in Web Workers.
Phương thức commit() của giao diện IDBTransaction sẽ commit transaction nếu nó được gọi trên một transaction đang active.
Lưu ý rằng bình thường commit() không cần phải gọi; transaction sẽ tự động commit khi mọi request đang chờ đã được xử lý và không có request mới nào được tạo. commit() có thể dùng để bắt đầu quá trình commit mà không cần chờ sự kiện từ các request đang chờ được phát ra.
Nếu gọi trên một transaction không active, phương thức này sẽ ném InvalidStateError DOMException.
Cú pháp
commit()
Tham số
Không có.
Giá trị trả về
Không có (undefined).
Ngoại lệ
InvalidStateErrorDOMException-
Được ném ra nếu trạng thái của transaction không active.
Ví dụ
const note = document.getElementById("notifications");
// mở transaction đọc/ghi, sẵn sàng để thêm dữ liệu
const transaction = db.transaction(["myDB"], "readwrite");
// báo cáo về kết quả mở 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.";
};
// tạo object store trên transaction
const objectStore = transaction.objectStore("myObjStore");
// thêm object newItem vào object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// báo cáo thành công của request (điều này không có nghĩa là mục
// đã được lưu thành công trong DB - để làm vậy bạn cần transaction.onsuccess)
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
// Buộc các thay đổi được commit vào cơ sở dữ liệu càng sớm càng tốt
transaction.commit();
Thông số kỹ thuật
| Specification |
|---|
| Indexed Database API 3.0> # ref-for-dom-idbtransaction-commit②> |
Tương thích trình duyệt
Xem thêm
- Dùng IndexedDB
- Bắt đầu transaction:
IDBDatabase - Dùng transaction:
IDBTransaction - Thiết lập một dải khóa:
IDBKeyRange - Truy xuất và thay đổi dữ liệu:
IDBObjectStore - Dùng cursor:
IDBCursor - Ví dụ tham khảo: To-do Notifications (Xem ví dụ trực tiếp).