The abort()
method of the IDBTransaction
interface rolls back all the changes to objects in the database associated with this transaction.
All pending IDBRequest
objects created during this transaction have their IDBRequest.error
attribute set to an AbortError
DOMException
.
In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. At the end, we abort any activity done under the current transaction using abort()
. For a full working example, see our To-do Notifications app (View example live).
const note = document.getElementById("notifications");
let db;
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.innerHTML += "<li>Database initialized.</li>";
db = DBOpenRequest.result;
addData();
};
function addData() {
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
const transaction = db.transaction(["toDoList"], "readwrite");
transaction.oncomplete = (event) => {
note.innerHTML +=
"<li>Transaction completed: database modification finished.</li>";
};
transaction.onerror = (event) => {
note.innerHTML +=
"<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};
const objectStore = transaction.objectStore("toDoList");
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
note.innerHTML += "<li>Request successful.</li>";
};
transaction.abort();
}