如何基于本地存储的另一个数据响应推迟XMLHttpRequest [英] How to defer a XMLHttpRequest based on another data response from local storage

查看:96
本文介绍了如何基于本地存储的另一个数据响应推迟XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//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();
    }
}

在上面这段代码中,我试图获得一些参数从本地存储变成了可变参数 ppsParams ,但是我希望只有在本地存储时才发送请求到 CLOUD_SERVER 请求失败,现在两者都正在执行,所以我该如何推迟XMLHttpRequest。

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.

推荐答案

看起来像 chrome.storage.local.get 是异步的,因此移动XMLHttpRequest代码如下所示:

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

这篇关于如何基于本地存储的另一个数据响应推迟XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆