Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IDBRequest: result, error, and event handlers

Read `result` after an IndexedDB request succeeds and `error` after it fails. A successful request does not mean that its transaction has committed.

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

Syntax

// Read-only members; do not read either while readyState is "pending".
// request.result
// request.error

request.onsuccess = (event) => { /* read request.result */ };
request.onerror = (event) => { /* read request.error */ };

// Alternative registration; event names omit the "on" prefix.
request.addEventListener("success", handleSuccess);
request.addEventListener("error", handleError);

IDBRequest.result/error/onsuccess/onerror covers two read-only properties and two event handler properties on an IndexedDB request. The request is not a Promise. IndexedDB is a Web API, not part of ECMAScript 2024; availability depends on the runtime. While readyState is "pending", reading either result or error throws an InvalidStateError DOMException. When readyState is "done", these properties can be read, but that state does not imply success. An IDBOpenDBRequest can report "done" during upgradeneeded, before the open operation fires its final success or error event.

Assign functions to request.onsuccess and request.onerror to handle success and error, respectively. Reassigning a property replaces its previous handler; use addEventListener() with event names that omit on to add separate listeners. On success, read request.result: its value depends on the operation. For example, add() reports the key through result, while get() can succeed with undefined if the key is absent. On success, request.error is null; on failure, it holds a DOMException and request.result is undefined. A try...catch around the call can catch a synchronous exception from that call, but not a later request failure.

The success event neither bubbles nor can be canceled. For a request in a transaction, error bubbles and by default causes the transaction to abort. Call event.preventDefault() in the handler for an expected, recoverable error to prevent that default abort. This does not turn the failed request into a success or stop the event from bubbling.

A successful write request does not mean the transaction has committed. Queue further requests while the transaction is active, for example directly in a request event handler. At the transaction level, listen for complete to detect commit and abort to detect rollback.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IDBRequest: success and error</title>
</head>
<body>
  <p>Open the browser developer console to see the output.</p>
  <script>
    (() => {
      const name = `cktis-idbrequest-${window.crypto.randomUUID()}`;
      const open = window.indexedDB.open(name, 1);

      open.onupgradeneeded = () => open.result.createObjectStore("items");
      open.onerror = () => console.error("open:", open.error.name);

      open.onsuccess = () => {
        const db = open.result;
        const tx = db.transaction("items", "readwrite");
        const store = tx.objectStore("items");

        function cleanup() {
          db.close();
          const deletion = window.indexedDB.deleteDatabase(name);
          deletion.onerror = () => console.error("cleanup:", deletion.error.name);
        }

        tx.oncomplete = () => {
          console.log("transaction: complete");
          cleanup();
        };
        tx.onabort = () => {
          console.error("transaction: aborted", tx.error?.name);
          cleanup();
        };

        const first = store.add("first", 1);
        first.onsuccess = () => console.log(`success: ${first.result}`);

        const duplicate = store.add("second", 1);
        duplicate.onerror = (event) => {
          const { name } = duplicate.error;
          if (name === "ConstraintError") event.preventDefault();
          console.log(`error: ${name}`);
        };
      };
    })();
  </script>
</body>
</html>

Result

success: 1
error: ConstraintError
transaction: complete

Save the example as an HTML file and serve it over HTTPS. Open the page in a browser with IndexedDB and `crypto.randomUUID()` available, and check the developer console for the output. The first `add()` reports key `1` through `result`; the second fails with `ConstraintError`. Calling `preventDefault()` prevents that error from aborting the transaction, so it can fire `complete`. After the transaction ends, the code closes the connection and requests deletion of the database created for this run.

Related lessons

  • JavaScript · Lesson 31 · Advanced · Version: 4

Sources