IDBTransaction:abort() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

注意:此功能在 Web Workers 中可用。

IDBTransaction 介面的 abort() 方法會回滾與此事務關聯的資料庫物件的所有更改。

在此事務期間建立的所有待處理的 IDBRequest 物件,其 IDBRequest.error 屬性都會被設定為一個 AbortError DOMException

語法

js
abort()

引數

無。

返回值

無(undefined)。

異常

InvalidStateError DOMException

如果事務已提交或已中止,則會丟擲此異常。

示例

在下面的程式碼片段中,我們開啟一個對資料庫的讀/寫事務,並向物件儲存新增一些資料。同時,請注意附加到事務事件處理程式的函式,用於報告事務成功或失敗時的結果。最後,我們使用 abort() 方法中止當前事務下的所有活動。有關完整的可執行示例,請參閱我們的 待辦事項通知 應用(線上檢視示例)。

js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Database initialized.";

  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "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("toDoList");

  // 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.";
  };

  // Abort the transaction we just did
  transaction.abort();
}

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbtransaction-abort②

瀏覽器相容性

另見