I am facing an issue where I am trying to extract values of a specific key from an indexed DB and store them in an array. The array seems to work correctly within the onsuccess function but appears empty after that. It seems like the asynchronous nature of the process is causing the problem, as indicated by the order in which the console logs two years[0]. I am struggling to grasp the sequence of events and how to achieve my desired outcome. I would greatly appreciate some guidance on identifying the problem and navigating towards a solution.
// initializing the array for storing values
var years = new Array();
// function to retrieve objects falling between specified years (low and high)
function getYears(low, high){
var request = window.indexedDB.open("matchDB", 1);
request.onerror = function(event) {console.log("onerror");}
request.onsuccess = function(event) {
var db = event.target.result;
var objectStore = db.transaction(["matches"], 'readonly').objectStore("matches");
var index = objectStore.index("year");
var range = IDBKeyRange.bound(low, high, true, true);
var request = index.openCursor(range);
request.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
var matchList = cursor.value;
// pushing the value of the key 'year' into the 'years' array
years.push(matchList.year);
console.log(years[0]); // this works
cursor.continue();
}
}
console.log(years[0]); // this returns undefined
}
}