make page等待在加载之前从缓存中读取

时间:2018-02-09 20:17:10

标签: javascript angular promise async-await local-storage

我有js函数,在我页面的标题部分调用。这个Js函数基本上使用异步ajax调用API,当它返回结果时,它将数据缓存在本地存储中(在页面中调用api的原因是节省页面加载的时间)。在我的html页面的body(这是一个角度应用程序)中,我想读取API的返回值并构造页面DOM。问题是有时候该值还没有在缓存中(API稍后返回)并且我不确定如何从本地存储中读取值等待,直到存在值。有关我如何使这项工作的任何建议?可能我需要将阅读从本地存储改为某种我不知道如何的承诺。

以下是我在标题中的内容:

<script>
    var xhttp = new XMLHttpRequest();
    this.xhttp.open("GET", "/api/orgData", true);
    this.xhttps.send();

getOrgData();

async function getOrgData() {
    var x = await resolveAfterOrgResponse();
    localStorage.setItem('OrgData', (x));
    console.log(x); 
}

function resolveAfterOrgResponse() {
        return new Promise(resolve => {
            this.xhttp.onreadystatechange = function () {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    console.log(xhttp.responseText);
                    resolve(xhttps.responseText);
                }
            };
        });
    }
</script>

在应用程序正文中,这就是我所拥有的:

config = JSON.parse(window.localStorage.getItem('orgData'));

提前致谢

0 个答案:

没有答案