gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:50:05 28 4
gpt4 key购买 nike

当 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com