IDBDatabase: transaction() 方法

Baseline 已廣泛支援

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

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

IDBDatabase 介面的 transaction 方法會立即返回一個包含 IDBTransaction.objectStore 方法的事務物件 (IDBTransaction),您可以使用它來訪問您的物件儲存。

語法

js
transaction(storeNames)
transaction(storeNames, mode)
transaction(storeNames, mode, options)

引數

storeNames

新事務範圍內物件儲存的名稱,宣告為字串陣列。只指定您需要訪問的物件儲存。如果您只需要訪問一個物件儲存,可以將它的名稱指定為字串。因此,以下兩行是等效的

js
db.transaction(["my-store-name"]);
db.transaction("my-store-name");

如果您需要訪問資料庫中的所有物件儲存,可以使用 IDBDatabase.objectStoreNames 屬性

js
const transaction = db.transaction(db.objectStoreNames);

傳入一個空陣列將丟擲異常。

mode 可選

可以在事務中執行的訪問型別。事務以三種模式之一開啟

readonly

為從物件儲存讀取事務開啟。這是預設模式。

readwrite

為從物件儲存讀取和寫入事務開啟。只有在需要寫入資料庫時才應使用此模式。

readwriteflush 非標準 實驗性

強制事務在 complete 事件發生之前重新整理到磁碟。這可能用於儲存無法稍後重新計算的關鍵資料。

options 可選

定義附加選項的物件,包括

durability

以下三種字串字面值之一

"strict"

使用者代理可能認為事務已成功提交,只有在驗證所有掛起更改已成功寫入持久儲存介質後才算完成。當資料丟失的風險大於其對效能和功耗的影響(與 relaxed 相比)時,推薦此選項。

"relaxed"

使用者代理可能認為事務已成功提交,只要所有掛起更改已寫入作業系統,無需後續驗證。這比 strict 提供了更好的效能,並推薦用於臨時資料,如快取或快速更改的記錄。

"default"

使用者代理應使用其儲存桶的預設永續性行為。如果未另行指定,則這是事務的預設行為。

返回值

IDBTransaction 物件。

異常

InvalidStateError DOMException

如果此 IDBDatabase 例項先前已呼叫 close() 方法,則會丟擲此異常。

NotFoundError DOMException

如果 'storeNames' 引數中指定的物件儲存已被刪除或移除,則會丟擲此異常。

TypeError

如果 mode 引數的值無效,則會丟擲此異常。

InvalidAccessError DOMException

如果函式使用空的物件儲存名稱列表呼叫,則會丟擲此異常。

示例

在此示例中,我們開啟資料庫連線,然後使用 transaction() 在資料庫上開啟一個事務。有關完整示例,請參閱我們的 待辦事項通知 應用(線上檢視示例)。

js
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 displayData() function to populate the task list with
  // all the to-do list data already in the IDB
  displayData();
};

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

// you would then go on to do something to this database
// via an object store
const objectStore = transaction.objectStore("toDoList");
// etc.

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbdatabase-transaction③

瀏覽器相容性

另見