Reputation: 2185
I have an IndexedDB containing properties of various elements on the page. I have an index on one of those properties and I use a key range to get a specific list of results.
var key = IDBKeyRange.bound(10, 20);
var cursor = store.index('property').openCursor(key);
The problem I have is with the cursor.onsuccess
function. It seems to execute for each result in the result set. Consequently, I can't execute a callback function once all of the results have been parsed.
cursor.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
if (cursor.value.prop1 > 30 && cursor.value.prop2 < 80) {
// Do stuff with result
someArray.push({
prop1: cursor.value.prop1,
prop2: cursor.value.prop2
}):
}
}
cursor.continue();
};
Upvotes: 0
Views: 1032
Reputation: 4129
Safest way to know that your action is finished is to use the transaction on complete event. This event is triggered after the cursor is closed.
transaction.oncomplete = function (event) {
console.log('transaction completed');
};
Also to be sure that no error occurred add event listener to transaction events on error and on abort.
transaction.onerror = function (event) {
console.log('transaction error');
};
transaction.onabort = function (event) {
console.log('transaction abort');
};
Upvotes: 1
Reputation: 2185
As it turns out, cursor.onsuccess
fires one last time with e.target.result
undefined. You can execute a callback function when this happens:
cursor.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
if (cursor.value.prop1 > 30 && cursor.value.prop2 < 80) {
// Do stuff with result
someArray.push({
prop1: cursor.value.prop1,
prop2: cursor.value.prop2
}):
}
} else {
// Execute code here
console.log('There are ' + someArray.length + ' elements in someArray.');
}
cursor.continue();
};
Upvotes: 1