0

sorry if this has been asked before but I couldn't find another question which answered mine. I'm trying to set a variable from a function which gets data from an AJAX call. However the function continues to run before I've got the data. How can I avoid this? If you run the functions below you can see that the data is coming out but not before the console.log for RDID value is being run. I need to set the RDID value. I also would appreciate some resources to learn this better.

var RDID = getData('https://domain.com?dataRequest', rdProviderLookup);

function getData(url, callback, optional) {
    var argLength = arguments.length;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send(null);
    xhr.onreadystatechange = function () {
    var DONE = 4; 
    var OK = 200; 
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            if (argLength == 3) {
                    callback(xhr.responseText, optional);
                } else {
                    callback(xhr.responseText);
                    }
            } else {
                console.log('Error ' + xhr.status);
                callback('Error');
            }
    }
    };
}
function rdProviderLookup(rdData) {
    var rdData = JSON.parse(rdData);
    var a = JSON.stringify(rdData.physicalStoreList[0].physicalStoreIdentifier.uniqueID);
    console.log('a= ' + a);
    return a;
}
console.log('RDID ' + RDID);
dust
  • 131
  • 1
  • 9
  • 1
    Returning a value from rdProviderLookup does not make it be returned from getData. You can only access the response from the callback. getData is asynchronous, the data is not available after the call to getData returns, only after the network request completes, that is, when the callback runs – Ruan Mendes Feb 08 '17 at 01:58
  • Make it synchronous, U can get it – Anil Talla Feb 08 '17 at 04:36

0 Answers0