IDBTransaction - Web API 接口参考 编辑

IDBTransacation接口由IndexedDB API提供,异步事务使用数据库中的事件对象属性。所有的读取和写入数据均在事务中完成。由IDBDatabase发起事务,通过IDBTransaction 来设置事务的模式(例如:是否只读readonly或读写readwrite),以及通过IDBObjectStore来发起一个请求。同时你也可以使用它来中止事务。

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702.) Previously in a readwrite transaction IDBTransaction.oncomplete was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further.

If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.

注意,事务在被创建的时候就已经开始,并非在发起第一个请求(IDBRequest)的时候。例如下面的例子:

var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
var objectStore2 = trans2.objectStore("foo")
var objectStore1 = trans1.objectStore("foo")
objectStore2.put("2", "key");
objectStore1.put("1", "key");

在代码执行后,object store 应该包含值 "2", 因为 trans2 应该在 trans1 之后执行。

Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

  • Abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. Can be prevented by using preventDefault() on the error event on the request.
  • Explicit abort() call from script
  • Uncaught exception in request's success/error handler
  • I/O error (actual failure to write to disk, e.g. disk detached, or other OS/hardware failure)
  • Quota exceeded
  • User agent crash

 

Note: 此特性在 Web Worker 中可用。
  <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="https://developer.mozilla.org/wiki/zh-CN/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text  x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25  121,20  121,30  111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="151" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/zh-CN/docs/Web/API/IDBTransaction" target="_top"><rect x="151" y="1" width="140" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text  x="221" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">IDBTransaction</text></a></svg></div>
  a:hover text { fill: #0095DD; pointer-events: all;}

属性

IDBTransaction.db 只读
当前事务所属的数据库连接。
IDBTransaction.error 只读
Returns a DOMException indicating the type of error that occured when there is an unsuccessful transaction. This property is null if the transaction is not finished, is finished and successfully committed, or was aborted with IDBTransaction.abort function.
IDBTransaction.mode 只读
用于隔离事务作用域内的object store中数据访问的模式。下方的常量章节给出了所有可用的值。默认值是 readonly.
IDBTransaction.objectStoreNames 只读
Returns a DOMStringList of the names of IDBObjectStore objects.

Event handlers

IDBTransaction.onabort 只读
The event handler for the abort event, fired when the transaction is aborted. This can happen due to:
  • bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint and there is no error handler on the request to call preventDefault() on the event,
  • an explicit abort() call from script
  • uncaught exception in request's success/error handler,
  • an I/O error (actual failure to write to disk, e.g. disk detached, or other OS/hardware failure), or
  • quota exceeded.
IDBTransaction.oncomplete 只读
The event handler for the complete event, thrown when the transaction completes successfully.
IDBTransaction.onerror 只读
The event handler for the error event, thrown when the transaction fails to complete.

方法

EventTarget继承

IDBTransaction.abort
放弃本次连接的transaction的所有修改,如果当前的transaction处于回滚完毕或完成状态,则会抛出一个错误事件。
IDBTransaction.objectStore
返回表示作为此事务作用域一部分的object store的 IDBObjectStore 对象。

模式常量

已废弃 Gecko 25 (Firefox 25 / Thunderbird 25 / SeaMonkey 2.22)
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

这些常量将不再可用——它们在Gecko 25中被移除。 你应该直接使用字符串常量来作为替代。 (bug 888598)

Transactions 可使用以下三种模式中的一种:

常量描述
READ_ONLY

"readonly"

(0 in Chrome)

允许读取数据,不改变。

READ_WRITE

"readwrite"

(1 in Chrome)

允许读取和写入现有数据存储,数据被改变。
VERSION_CHANGE

"versionchange"

(2 in Chrome)

允许执行任何操作,包括删除和创建对象存储和索引。
此模式是用于开始使用IDBDatabasesetVersion()方法更新版本号事务。 这种模式的事务无法与其它事务并发运行。
这种模式下的事务被称为“升级事务”。

即使目前这些常量已经被废弃,但如果你需要使用它,则需要提供向下兼容方案(in Chrome the change was made in version 21)。你应当防止出现对象不存在的情况:

var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" };

Example

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. For a full working example, see our To-do Notifications app (view example live.)

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

DBOpenRequest.onsuccess = function(event) {
  note.innerHTML += '<li>Database initialised.</li>';

  // 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
  var 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
  var transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = function(event) {
    note.innerHTML += '<li>Transaction completed: database modification finished.</li>';
  };


  transaction.onerror = function(event) {
  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
  };

  // create an object store on the transaction
  var objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  var objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = function(event) {
    // report the success of our new item going into the database
    note.innerHTML += '<li>New item added to database.</li>';
  };
};

Specifications

SpecificationStatusComment
Indexed Database API
IDBTransaction
Recommendation 

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23webkit
24
10 moz
16.0 (16.0)
10, partial157.1
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.422.0 (22.0)1.0.11022未实现

Known browser issues

Older versions of Google Chrome serialise all transactions. So even if you have only read-only transactions and no read-write transaction, your transactions are executed one at a time. Any subsequent transactions are not executed until read-only transactions are completed. For the status, see bug 64076.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:66 次

字数:20111

最后编辑:6年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文