I have this JavaScript code that iterates through an indexedDB object store and returns all of the objects it contains.
I need to wait until the method is finished before I continue on with my code because I need to make use of the array variable that the code will be pushing the objects to.
One way to ensure synchronous execution is to nest call back functions.
Rather than doing that though, I thought I could just add a while loop that iterates indefinitely to the end of the method and breaks when the variable I need has been filled.
function getAllObjects(){
var tags=[];
var openRequest = indexedDB.open("Tags",CURRENT_DB_VERSION);
openRequest.onsuccess = function(event){
var db = event.target.result;
var objectStore = db.transaction("domains").objectStore("domains");
objectStore.openCursor().onsuccess= function(event){
var cursor= event.target.result;
if(cursor){
console.log(cursor.value);
tags.push(cursor.value);
cursor.continue();
}
}
db.onerror = function(event){
console.log("an error bubbled up during a transaction.");
};
};
openRequest.onerror = function(event){
console.log("error opening DB");
};
while(tags.length==0){//wait for async to finish
}
return tags;
}
When I do this though, my code never exits the while loop. Why is this?