I am having a challenge with indexedDB keys not matching the record numbers. To correct this I need to cycle through the records and reset the ID to match the index. I am trying to form an array that contains all the record IDs with a cursor, but it returns immediately.
How can I wait until all ids have been gathered before returning the array?
So far I have this.
async function getKeyIndex(s) {
var i = await countDBRecords(s); // my own f() - no problem here.
var dbStore = [];
var c = 0;
var objectStore = db.transaction(s).objectStore(s);
objectStore.openCursor().onsuccess = event => {
var cursor = event.target.result;
if (cursor) {
console.log("Name: " + cursor.key + " - id: " cursor.value.id);
dbStore[c]= cursor.value.id;
c++;
if(c<i){cursor.continue();}
else{return(dbStore)};
}
};
}
Fired by:
keyIndex = await getKeyIndex('conversations');
console.log("Database keys " + keyIndex);
But the function always returns an undefined value as the onsuccess events have yet to complete before the function ends.
How can I keep the function from returning the array before it is populated?
returnstatement is for the inner function you assign to.onsuccess, not the outergetKeyIndexfunction. Return a Promise from the outer function that gets resolved in the.onsuccesshandler.returnstatement.