javascript - 等待 OpenWeather 函数,然后运行另一个函数
问题描述
我正在构建一个时间和天气应用程序。我有两个功能。等待 getWeather() 的 showtime()。常量在 getWeather() 中记录正常,但是当我尝试在 showtime() 中检索相同的常量时,我得到未定义的... Fiddle。
<div class="weekday"></div>
const weekday = document.querySelector('.weekday');
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur','Fri', 'Sat', 'Sun'];
setInterval(() => {
const d = new Date();
const day = days[d.getDay()];
async function showtime() {
await getWeather();
console.log(sunriseTime); // returns undefined
console.log(day) // logs fine, returns Wednesday.
weekday.innerHTML = day + ', Sunrise at: ' + sunriseTime;
}
showtime();
}, 1000);
//
const openweather_api = "https://api.openweathermap.org/exampleexample";
async function getWeather() {
console.log('run weather function first')
const response = await fetch(openweather_api);
const json = await response.json();
const sunriseTime = `${json.sys.sunrise}` // logs sunrise time in seconds.
}
getWeather(); // runs fine and retrieves values from Open Weather Json.
解决方案
这是因为变量范围。
您在getWeather的函数范围内声明了变量sunrisetime
所以,不能在outerscope中调用
const b = 2;
console.log(a);// undefined because it is not declared in this scope
const foo = () => {
const a = 1;
console.log(a);// 1
console.log(b);// 2
}
/*************************************************************************/
// a solution to this problem can be
let c;
const getInnerVariable = VAR => {
return VAR;
}
const foo = () => {
const a = 1;
console.log(a);// 1
c = getIneerVariable(a);
}
在此处阅读有关 JS 中的变量提升的更多信息
推荐阅读
- python-3.x - 如何修复 spaCy en_model 与当前 spaCy 版本(2.3.2)不兼容?
- pandas - 如何从另一个 df 列中生成唯一值的 df?
- python-3.x - Selenium Pytest 方法中缺少参数
- python - 如何更改从文件中读取的列表,以便在程序运行时更改,但在程序结束时重置?
- sql - Postgres 不同的内部连接(一对多),连接表上有 n 个约束
- mongodb - MongoDB - 复杂嵌套数组中的 $lookup
- java - 如何播放 mp4 JavaFx MediaPlayer
- azure - Azure WebJob 部署
- javascript - React Native 在所有屏幕中传递数据
- c++ - 如果我像对待 C++ 代码一样对待我的 C 代码,它会像往常一样运行吗?