1
//function to download pps_compress.txt from cloud server for global parameter set PPs
function get_pps_params()
{

    chrome.storage.local.get(['ppsParams'], function(result) {
        if (typeof(result) !== "undefined" && result != null){
            ppsParams = _base64ToArrayBuffer(result.ppsParams);
            console.log(ppsParams);
            dfd_pps.resolve();
            return;
        }
    });

    if(ppsParams == null)
    {
        var oReq = new XMLHttpRequest();
        oReq.open("GET", CLOUD_SERVER + 'get_pps_params', true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function (oEvent) {
            console.log("Got pps params compressed!");
            ppsParams = oReq.response; // Note: not oReq.responseText
            chrome.storage.local.set({ppsParams: _arrayBufferToBase64(ppsParams)});
            dfd_pps.resolve();
        };

        oReq.send();
    }
}

In the above piece of code I am trying to get some parameters into the varaible ppsParams from local storage, but I want to send request to the CLOUD_SERVER only if the local storage request fails, right now both are being executed, so how can I defer the XMLHttpRequest.

bawejakunal
  • 1,678
  • 2
  • 25
  • 54

1 Answers1

1

looks like chrome.storage.local.get is asynchronous, so move the XMLHttpRequest code as shown below

function get_pps_params()
{

    chrome.storage.local.get(['ppsParams'], function(result) {
        if (typeof(result) !== "undefined" && result != null){
            ppsParams = _base64ToArrayBuffer(result.ppsParams);
            console.log(ppsParams);
            dfd_pps.resolve();
        }
        if(ppsParams == null)
        {
            var oReq = new XMLHttpRequest();
            oReq.open("GET", CLOUD_SERVER + 'get_pps_params', true);
            oReq.responseType = "arraybuffer";

            oReq.onload = function (oEvent) {
                console.log("Got pps params compressed!");
                ppsParams = oReq.response; // Note: not oReq.responseText
                chrome.storage.local.set({ppsParams: _arrayBufferToBase64(ppsParams)});
                dfd_pps.resolve();
            };

            oReq.send();
        }
        return;
    });
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Thanks this works as expected, this being the callback method isn't there any other method to wait for a function to complete before executing another piece of code ? – bawejakunal Jul 11 '15 at 15:40
  • you could use promises - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise , but that would be overkill for this simple case – Jaromanda X Jul 11 '15 at 15:41