I seem to be getting a dirty read from an IndexedDB index. Is this possible?

只愿长相守 提交于 2019-12-24 20:27:10

问题


I have some js that does a put to IndexedDB (in Chrome) using a readwrite transaction, then immediately queries from the same indexedDB objectstore using an index and a readonly transaction. Sometimes, the results I get back do not include the changes from my put and other times they. Is this sort of dirty ready to be expected in IndexedDB? Is there a way to avoid it?

Perhaps it's because I'm using 2 different txns and should be using just one (the reason for that is these calls are actually part of an api that separates puts and queries into different api calls that each have their own txns)? Still, seems like the first txn should be done and committed before my second one starts.

My pseudocode looks like this:

var txn = idb.transaction([DOC_STORE], "readwrite");
var putRequest = txn.objectStore(DOC_STORE).put(myDoc);
putRequest.onsuccess = function (e) {
    var txn2 = idb.transaction([DOC_STORE], "readonly");
    var store = txn2.objectStore(DOC_STORE);
    var anotherRequest=store.index.openCursor();
    .... walk the cursor here. Sometimes I don't see my changes from my put
};

回答1:


You have to wait for the write transaction to complete. It comes later than request success event.

var txn = idb.transaction([DOC_STORE], "readwrite");
var putRequest = txn.objectStore(DOC_STORE).put(myDoc);
txn.oncomplete = function (e) {
    var txn2 = idb.transaction([DOC_STORE], "readonly");
    var store = txn2.objectStore(DOC_STORE);
    var anotherRequest=store.index.openCursor();
    .... walk the cursor here. You will see see your all changes from your put
};

Alternatively, you can use request success in same transaction.

var txn = idb.transaction([DOC_STORE], "readwrite");
var putRequest = txn.objectStore(DOC_STORE).put(myDoc);
putRequest.onsuccess = function (e) {
    var store = txn.objectStore(DOC_STORE);
    var anotherRequest=store.index.openCursor();
    .... walk the cursor here. You will see see your all changes from your put
};


来源:https://stackoverflow.com/questions/15240232/i-seem-to-be-getting-a-dirty-read-from-an-indexeddb-index-is-this-possible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!