我已经使用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();
}
发布于 2019-06-12 03:43:55
在搜索函数中,您正在推送到promise之外的searches
数组,这意味着它可能在promise有机会解析之前就发生了
https://stackoverflow.com/questions/56550693
复制相似问题