gpt4 book ai didi

javascript - 等待 OpenWeather 函数,然后运行另一个函数

转载 作者:行者123 更新时间:2023-12-02 21:10:54 33 4
gpt4 key购买 nike

我正在构建一个时间和天气应用程序。我有两个功能。 showtime() 正在等待 getWeather()。常量在 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

所以,不能在外层作用域中调用


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 中变量提升的更多信息 Here

关于javascript - 等待 OpenWeather 函数,然后运行另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61099397/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com