Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don't want to set the variable inside the fetchData function itself. What would be the best approach to assign the variable value while waiting for the fetchData function? Do I need to implement some kind of callback, or perhaps use a promise? Should I consider setting the async argument of window.XMLHttpRequest.open to false?

'use strict';

function fetchData() {
    var prodData;

    if (window.XMLHttpRequest) {
        prodData = new XMLHttpRequest();
        prodData.overrideMimeType('application/json');
        prodData.open('GET', 'products.json', true);
        prodData.send();

        prodData.onreadystatechange = function () {
            if (prodData.readyState === 4 && prodData.status === 200) {
                return prodData.responseText;
            } else {
                return false;
            }

        };
    }
}

var myData = fetchData();

// later I shall use this data like so...

doSomethingWithMyData(myData);

Answer №1

Consider utilizing the promise-based asynchronous approach.

This method involves returning an object from the function fetchData that allows subscribing to progress of async operations:

fetchData().done(function(data) {
  // Perform actions upon successful completion of async operation
});

jQuery offers a solid implementation of this technique.

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

Should I submit two requests to the ActionResult?

In my ASP.net MVC project, I have implemented different ajax requests to the same action result based on user-selected filter options. For example: $(document).on("click", "#filter_reset_button", function () { var url = "/Admin/Index"; ajaxReque ...

Directive for Angular JS that creates a custom table

Working on a project that involves a significant amount of serial true/false data to be displayed in various ways. Developed a directive to pass in the model, table header, and an important aspect - the number of columns. <serial-checkbox-table title=" ...

Issues with image uploads in Node.js database storage

Trying to update an image using the put method is resulting in a 'filename' undefined error. Interestingly, the image updates successfully when editing without changing the image. The code snippet below shows the implementation: app.put('/a ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Can you clarify the distinction between calling subscription.unsubscribe() and subscription.remove()?

Currently, I am working with Angular 5 and have successfully subscribed to an observable with the use of the subscribe() method. My concern pertains to whether simply calling the unsubscribe() method on the subscription will be adequate for cleaning up all ...

Using a variable in a Joomla module to create a JavaScript object with PHP

I am currently developing a Joomla module that features a progress bar utilizing the ProgressBar.js plugin. Since this module is designed to load multiple objects on a single page, hardcoding the IDs of these objects is not feasible. To address this, I uti ...

What methods can be used to perform unit testing on a controller within an AngularJS Directive?

My command is: window.map.directive('dosingFrequencies', [ function() { return { restrict: 'E', scope: true, templateUrl: '/views/directives/dosingFrequencies.html', controller: function($scope, ...

My goal is to populate all of these elements with Javascript

My goal is to have all the boxes filled with "excellent": https://i.sstatic.net/oHW6W.png let a = document.querySelectorAll('.select2-choice'); a.forEach((e) => {console.log(e)}) a.forEach((e) => {e.innerHTML = ` <span ...

Differences between Cross-domain Ajax calls and PHP requests

After reading up on cross-origin requests, I came across this resource link: https://coinmap.org/api/v1/venues/?mode=list It's interesting how I can successfully make a request to this link using PHP and retrieve data, but encounter an error when try ...

Guidance on incorporating CSS into ES6 template literals within a react framework

I am trying to implement the Material UI stepper in my React application. The step content is set up as a string literal. My goal is to include CSS styling for paragraphs within the step content. Many online resources suggest using \n to add a line ...

How can JSON data size be minimized effectively?

We have encountered an issue with high throughput on some of our data stores. Our current approach involves serializing POJOs to JSON using Jackson, but we are looking for alternative methods to compress the JSON data. Initially, we considered using BSON ...

JavaScript code that formats input prices, detects any formatting errors

Before jumping to conclusions, I want to clarify that I am not inquiring about the actual process of formatting the price. Instead, I am seeking guidance on where I may be going wrong or what steps I need to take in order to achieve the desired outcome. I ...

Can firebase and express be integrated seamlessly?

I'm a newcomer to Express and I want to create a REST API with express.js that utilizes Firebase as its database. Can these two technologies actually work together? Here is the code snippet I tried: cons ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

Having issues with your JQuery code?

I am attempting to locate a cell within a table that contains the class 'empty'. My goal is to then utilize a code snippet to obtain the id (cell number) and determine which cells are adjacent to it. As part of my test, I am experimenting with t ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method. The specific location where I want this execution to happen: <Button variant="contained" onClick={saveData}&g ...