Indexeddb:onsuccess和oncomplete之间的差异?

jer*_*nho 5 database indexeddb

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

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

tr = db.transaction(os_name,'readwrite');
os = tr.objectStore();
Run Code Online (Sandbox Code Playgroud)

情况1 :

r = os.openCursor();
r.onsuccess = function(){
    if(r.result){
        callback_for_result_fetched();
        r.result.continue;
    }else callback_for_transaction_finish();
}
Run Code Online (Sandbox Code Playgroud)

案例2:

tr.oncomplete = callback_for_transaction_finish();
Run Code Online (Sandbox Code Playgroud)

如果它们两者的工作方式相似则是浪费.所以你能告诉我,他们之间有什么区别吗?

bul*_*ley 8

虽然这是事实,这些回调函数类似的,它们是不一样的:之间的差别onsuccess,并oncomplete是交易complete,但要求,这是对这些事务进行的,是successful.

oncomplete仅在规范中定义为与事务相关.事务没有onsuccess回调.

  • 是的,这意味着交易已超出范围并已提交 (2认同)

Gul*_*rYA 8

很抱歉提出了一个很老的线索,但它的质疑是一个很好的起点......

我找了一个类似的问题,但在一个不同的用例,实际上没有找到好的答案,甚至没有误导的答案.

想想一个用例,当你需要在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 });
Run Code Online (Sandbox Code Playgroud)

这个理解的线索可以在以下W3C 规范声明中找到:

要确定事务是否已成功完成,请侦听事务的完整事件而不是特定请求的成功事件,因为事务在成功事件触发后仍可能失败.