我制作了一个小型网页,从" yahoo天气" API中获取信息并在页面上显示Divs。
这是JS:
const url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
let data = 1;
const getWeather = async function() {
const fetchWeather = await fetch(url);
const result = await fetchWeather.json();
return data=result;
}
getWeather();
const showData = async function(info) {
let html = '';
const newInfo = info.query.results.channel.item.forecast.map((item, index) => {
html += `<div id='item${index}'><p>Date: ${item.date}</p>`;
html += `<p>Day: ${item.day}</p>`;
html += `<p>Highest temp: ${item.high}</p>`;
html += `<p>Lowest temp: ${item.low}</p></div>`;
return html;
});
}
const display = async function() {
const info = await showData(data);
weatherInfo.innerHTML = data;
}
display();
我的目标是,当页面加载时,它显示了从API返回的承诺中收集的信息。
我得到了此错误:未经读取(在Promise(typeError:无法读取未定义的
的属性'结果'据我所知,在调用" display(("时,变量"数据"还没有任何内容。
我要实现的是Display((只有在定义"数据"之后才能工作,但没有循环或类似的内容。
任何帮助将不胜感激!
据我所知,当调用" display(("时,变量"数据"还没有任何内容。
是。不要完全使用全局data
变量 1 。getWeather
返回将通过数据实现的承诺,因此您确切知道何时可用:
getWeather().then(display);
async function getWeather () {
const fetchWeather = await fetch(url);
const result = await fetchWeather.json();
return result; // drop the `data =` assignment
}
async function display(data) {
// ^^^^
const info = await showData(data);
weatherInfo.innerHTML = info;
}
另外,尤其是当您不想使用then
链时,只需将const data = await getWeather();
放在display
函数中。
1:如果您坚持要在全局范围中存储数据,因为您想在多个位置使用它,请将 Promise 放在变量中的数据中,而不是结果本身。
这是我的solutiuon:
const url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
const getWeather = async function() {
const fetchWeather = await fetch(url);
return await fetchWeather.json();
}
const showData = async function(info) {
let html = '';
info.query.results.channel.item.forecast.map((item, index) => {
html += `<div id='item${index}'><p>Date: ${item.date}</p>`;
html += `<p>Day: ${item.day}</p>`;
html += `<p>Highest temp: ${item.high}</p>`;
html += `<p>Lowest temp: ${item.low}</p></div>`;
});
return html;
}
const display = async function() {
const data = await getWeather();
const info = await showData(data);
weatherInfo.innerHTML = info;
}
display();
https://plnkr.co/edit/1b0fpbji7y6szpodpdjy?p = preview