How to defer a XMLHttpRequest based on another dat

2020-04-21 03:00发布

问题:

//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.

回答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;
    });
}