Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IndexedDB transaction events: complete, abort, and error

Use `complete` and `abort` to determine the outcome of a whole IndexedDB transaction, and `error` to diagnose a failed individual request.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

tx.addEventListener("complete", onComplete);
tx.addEventListener("abort", onAbort);
tx.addEventListener("error", onRequestError);

// Property-based alternatives:
tx.oncomplete = onComplete;
tx.onabort = onAbort;
tx.onerror = onRequestError;

// Read the transaction's error, if any:
const failure = tx.error;

// To explicitly roll back a transaction that can still be aborted:
tx.abort();

IDBTransaction.complete/abort/error groups three event names. Listen on the transaction tx with addEventListener() or the oncomplete, onabort, and onerror handler properties. complete means the whole transaction committed. An individual request's success does not: a later failure can still roll back that request's changes. A commit does not necessarily mean the bytes have been flushed to disk; that depends on the durability setting and runtime.

abort means the transaction ended without committing and its changes were rolled back. The event bubbles to IDBDatabase and is not cancelable. It can follow an explicit tx.abort() call or a failure. In the abort handler, read tx.error: this read-only property holds a DOMException describing the failure, or null, as after an explicit tx.abort().

An error event originates on an IDBRequest and bubbles through tx to the database. Read event.target.error for the request's cause, not tx.error, which may still be null. By default, a request error aborts the transaction. For an expected error, call event.preventDefault() while handling the event to prevent that particular abort; stopPropagation() alone does not. The request still failed. Use complete or abort for the final transaction outcome.

IndexedDB is a web platform API, not part of ECMAScript 2024. Queue requests while the transaction is active, such as immediately after creation or in its request handlers. After awaiting unrelated work such as fetch(), the transaction may no longer accept requests. Availability depends on the runtime and storage policy.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IndexedDB transaction events</title>
</head>
<body>
<pre id="output"></pre>
<script>
void (async () => {
  const output = document.getElementById("output");
  function log(line) {
    console.log(line);
    output.textContent += `${line}\n`;
  }

  const name = `cktis-tx-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  const indexedDB = window.indexedDB;
  const open = indexedDB.open(name, 1);
  open.onupgradeneeded = () => open.result.createObjectStore("items");
  const db = await new Promise((resolve, reject) => {
    open.onsuccess = () => resolve(open.result);
    open.onerror = () => reject(open.error);
  });

  function write(label, cancelError) {
    return new Promise((resolve) => {
      const tx = db.transaction("items", "readwrite");
      tx.oncomplete = () => resolve("complete");
      tx.onabort = () => resolve(`abort: ${tx.error?.name ?? "no error"}`);
      tx.onerror = (event) => {
        log(`${label} error: ${event.target.error.name}`);
      };

      const items = tx.objectStore("items");
      items.add("first", label);
      const duplicate = items.add("second", label);
      if (cancelError) {
        duplicate.onerror = (event) => {
          if (duplicate.error.name === "ConstraintError") event.preventDefault();
        };
      }
    });
  }

  try {
    for (const [label, cancelError] of [["rollback", false], ["recover", true]]) {
      log(`${label} ${await write(label, cancelError)}`);
    }

    const values = await new Promise((resolve, reject) => {
      const tx = db.transaction("items", "readonly");
      const items = tx.objectStore("items");
      const rolledBack = items.get("rollback");
      const recovered = items.get("recover");
      tx.oncomplete = () => resolve([rolledBack.result, recovered.result]);
      tx.onabort = () => reject(tx.error ?? new Error("Read aborted"));
    });
    log(`stored: ${values.map(String).join(",")}`);
  } finally {
    db.close();
    await new Promise((resolve, reject) => {
      const deletion = indexedDB.deleteDatabase(name);
      deletion.onsuccess = () => resolve();
      deletion.onerror = () => reject(deletion.error);
    });
  }
})().catch(console.error);
</script>
</body>
</html>

Result

rollback error: ConstraintError
rollback abort: ConstraintError
recover error: ConstraintError
recover complete
stored: undefined,first

Serve the example as an HTML page over HTTPS and open it in a browser where IndexedDB is available and storage is permitted. Both transactions report `ConstraintError` for a duplicate key. The first rolls back its initial write; the second commits it because the error handler prevents the default action.

Related lessons

  • JavaScript · Lesson 20 · Intermediate · Version: 3
  • JavaScript · Lesson 21 · Intermediate · Version: 3

Sources