首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何防止此fetch API搜索栏在通过localStorage存储新查询之前加载旧查询?

如何防止此fetch API搜索栏在通过localStorage存储新查询之前加载旧查询?
EN

Stack Overflow用户
提问于 2019-06-12 03:40:14
回答 1查看 23关注 0票数 -1

我已经使用fetch()为NASA API创建了一个搜索栏。

加载并显示第一个搜索查询的图像,但需要多次触发搜索按钮的事件侦听器才能显示新的查询。似乎旧的响应在localStorage中更新之前就被访问了,或者类似的东西?

下面是Codepen:https://codepen.io/ana-ana/pen/orgbjB

我已经尝试在searches.push(JSON.parse(localStorage.getItem('response')));上使用setTimeout来防止这个问题。我还多次尝试触发execute函数。我还尝试在每次运行函数时将json响应以不同的名称存储在localStorage中。

function clear(){
    document.getElementById('images').innerHTML='';
}
var searches = [];
function search(inquiry){
console.log(fetch(inquiry));
        fetch(inquiry)
                  .then(function(response) {
                    var status = response.status;
                    return response.json();
                  })
                  .then(function(jsonResponse) {
                    localStorage.setItem('response', JSON.stringify(jsonResponse));
                  });
searches.push(JSON.parse(localStorage.getItem('response')));
}
function display(){
    for(i = 0; i<searches[searches.length - 1].collection.items.length; i++){
        var img = document.createElement('img');
        img.src = searches[searches.length - 1].collection.items[i].links[0].href;
        document.getElementById('images').appendChild(img);
    }   
}


document.getElementById('btn').addEventListener('click', execute);

function execute(){
    clear();
    search(`https://images-api.nasa.gov/search?q=${document.getElementById('searchbar').value}`);
    console.log(searches[searches.length - 1]);
    display();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-12 03:43:55

在搜索函数中,您正在推送到promise之外的searches数组,这意味着它可能在promise有机会解析之前就发生了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56550693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档