Is it possible to access values from an IndexedDB object store key stored in an array without global access?

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
}
}

Answer №1

When working with asynchronous requests, it's important to understand how callback functions like request.onsuccess operate. This particular function is triggered upon completion of the request, but keep in mind that you are merely assigning the function to the property and not executing it immediately. The execution may occur seconds later.

Following the definition of this function, any subsequent code will continue to run. In the provided code snippet, console.log(years[0]) is called right after, resulting in the output of "undefined" since the callback has not been executed yet. To handle interactions with the "years" array properly, ensure all related code resides within the onsuccess callback block.

If organizing all code inside the callback seems overwhelming, consider creating a separate method and invoking it from within the callback function for better structuring.

function handleRequest(evt) {
    var cursor = evt.target.result;
     if (cursor) {
        var matchList = cursor.value;
        years.push(matchList.year);
        console.log(years[0]);
        cursor.continue();
     }
}

var request = index.openCursor(range);
  request.onsuccess = function(evt) {
     handleRequest(evt);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

Is it possible to change individual pixels within a canvas without the need to duplicate the entire buffer?

Is it possible to directly alter individual pixels within a canvas, rather than retrieving the entire buffer using ctx.getImageData and then pasting it back with ctx.putImageData? This is crucial in order to avoid the costly process of copying data every ...

A function designed to retrieve all nearby values within a list

After spending quite some time trying to tackle the problem at hand, I find myself stuck. I am dealing with a list of various values, such as: list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905) I am looking to create a function that can identify a ...

Leveraging Vue.js's capabilities with an external setup file

Is it feasible for a Vue App to access an external configuration file? I envision a setup where I deploy the application along with the config file; then, I should be able to modify the configuration in the external file without needing to rebuild the enti ...

Angular: Issue with Controller Constructor Function Executing Repeatedly

My concern lies in the fact that the Controller constructor seems to be executing multiple times. It appears that if I have 2 Directives associated with a specific Controller, it runs 2 + 1 times, and for 3 Directives, it runs 3 + 1 times...and so on. This ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

Include the url of the html file in your JavaScript code

I have a piece of code that I want to include in my JavaScript instead of HTML. The code is as follows: <script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script> Since all my functions are written in JavaScript, I ...

Is there a way to adjust a 5-minute countdown interval timer by 1 minute in a react JS application?

I am in need of creating a 5-minute interval timer using react JS, with a 1-minute offset. The current timer I have functions like this: 1:00 => 1:05 => 1:10 => 1:15 => 1:20. However, I require it to be adjusted to display: 1:01 => 1:0 ...

Experimenting with animating an element through onClick event using JavaScript

I would like to create an animated div using JavaScript that activates on click. <div class="Designs"> <p>Designs</p> <div class="Thumbnails" data-animation="animated pulse"> <a href=" ...

Obtaining the term ID from a name using taxonomy_get_term_by_name in Drupal

I attempted to retrieve a termId from a term using the code below: $term = taxonomy_get_term_by_name($address_string); $termId = $term[0]->tid; Although there is one result, it is showing as term[30], causing the code above to fail. I assumed I ...

I'm having trouble displaying the result of my calculation in the code. Could it be because I forgot to include an output tag?

I am attempting to develop a Miles Per Gallon (MPG) calculator using Javascript. However, I'm encountering difficulties with displaying the results once the "Calculate" button is pressed. <html> <head> <title> MPG Calculator </ti ...

How can one determine if a new document was created by Mongoose's upsert feature?

My code in node.js/express.js looks like this: var User = mongoose.model('User'); var usersRouter = express.Router(); usersRouter.put('/:id', function(req, res) { req.body._id = req.params.id; var usr = new User(req.body); ...

Error message: "jQuery is not defined and occurs exclusively in Chrome."

I've been using the following code to asynchronously load my JavaScript in the head section: <script type='text/javascript'> // Add a script element as a child of the body function downloadJSAtOnload() { var element4= document.creat ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

Is it possible to request/scrape pages from the client side?

Let me present the issue at hand: I am currently managing a web application that serves as a notification system which updates frequently. This application is operational on several local computers, each of which solely display information without any inp ...

Utilizing Conditional Styling for an Array of Objects within a Textarea in Angular 6

My array contains objects structured as follows: list =[ { name:"name1", value:true } { name:"name2", value:false } { name:"name3", value:true } { name:"name4", value:false ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...

improve your AJAX implementation in Django

Recently, I implemented some AJAX functionality in a Django application that I have been developing. Coming from a background in Ruby on Rails, I haven't had much experience with pure JavaScript. So, inspired by Rails' partials, I came up with ...