database - Indexeddb:onsuccess 和 oncomplete 之间的区别?

标签 database indexeddb

当 IndexedDB 事务完成或成功时,我使用两个不同的回调事件来响应:

假设... db:IDBDatabase 对象,tr:IDBTransaction 对象,os:IDBObjectStore 对象

tr = db.transaction(os_name,'readwrite');
os = tr.objectStore();

案例 1:

r = os.openCursor();
r.onsuccess = function(){
    if(r.result){
        callback_for_result_fetched();
        r.result.continue;
    }else callback_for_transaction_finish();
}

案例二:

tr.oncomplete = callback_for_transaction_finish();

如果两者的工作方式相似,那就太浪费了。那你能告诉我,它们之间有什么区别吗?

最佳答案

很抱歉提出了一个很旧的话题,但提问是一个很好的起点......

我已经在寻找一个类似的问题,但在一个有点不同的用例中,实际上没有找到好的答案,甚至没有找到误导性的答案。

考虑一个用例,当您需要对 objectStore 进行多次写入甚至多次写入时。您绝对不希望管理每个单独的写入及其自身的成功和错误事件。这就是事务的含义,这是 indexedDB 的(正确的)实现:

var trx = dbInstance.transaction([storeIdA, storeIdB], 'readwrite'),
    storeA = trx.objectStore(storeIdA),
    storeB = trx.objectStore(storeIdB);

    trx.oncomplete = function(event) {
        // this code will run only when ALL of the following requests are succeed
        // and only AFTER ALL of them were processed
    };
    trx.onerror = function(error) {
        // this code will run if ANY of the following requests will fail
        // and only AFTER ALL of them were processed
    };

    storeA.put({ key:keyA, value:valueA });
    storeA.put({ key:keyB, value:valueB });
    storeB.put({ key:keyA, value:valueA });
    storeB.put({ key:keyB, value:valueB });

这种理解的线索可以在 W3C 的以下声明中找到 spec :

To determine if a transaction has completed successfully, listen to the transaction’s complete event rather than the success event of a particular request, because the transaction may still fail after the success event fires.

关于database - Indexeddb:onsuccess 和 oncomplete 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11149388/

相关文章:

java - DbUnit 的 XML 文件中的变量值

database - 根据与 Laravel 和 Eloquent 的关系进行计数和排序

java - 在 Android 中从浏览器外部访问 Web Storage 或 IndexedDB

google-chrome - Chrome StorageManager API 报告配额远大于预期

php - 触发更新每个 CRUD 操作的字段 laravel 5 Query Builder

database - 如何通过 Cypher Neo4j 中的其他 Prop 对 Node Prop 的值进行分组?

mysql - 将表与数据库中的 BOOLEAN 进行比较

javascript - 文件系统访问 API : is it possible to store the fileHandle of a saved or loaded file for later use?

google-chrome - 我或我的应用如何知道 Chrome 正在丢弃索引的数据库项目?

google-chrome-extension - Chrome 扩展程序是否可以访问由特定域创建的 IndexedDB 数据库?