0

I have a problem, I have written a nice function that returns a dataset from a local JSON file on my server. I wish to use the returned data by setting this to a variable to I can pass it to other functions later however due to the asynchronous nature of AJAX my variable will always be set to undefined as the variable is set before the dataset from my function is returned. I don't want to set my variable inside my fetchData function, what is the best way to assign my variable value here whilst waiting for the fetchData function. Should I return some kind of callback or does this need a promise of some kind or should I set 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);
Mark Sandman
  • 3,293
  • 12
  • 40
  • 60

1 Answers1

0

I suggest you the promise-based asynchronous pattern.

That is, you provide an object as return value of fetchData that allowing you to subscribe to asynchronous operation progress:

fetchData().done(function(data) {
  // Do stuff when async operation completed successfully
});

jQuery has a decent implementation for this pattern.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206