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

Javascript 等待OpenWeather函数,然后运行另一个函数,javascript,Javascript,我正在构建一个时间和天气应用程序。我有两个功能。等待getWeather()的showtime()。这些常量在getWeather()中记录得很好,但当我尝试在showtime()中检索相同的常量时,却没有定义 const weekday=document.querySelector('.weekday'); 常日=[‘星期一’、‘星期二’、‘星期三’、‘星期四’、‘星期五’、‘星期六’、‘星期日’]; 设置间隔(()=>{ const d=新日期(); const day=days[d.ge

我正在构建一个时间和天气应用程序。我有两个功能。等待getWeather()的showtime()。这些常量在getWeather()中记录得很好,但当我尝试在showtime()中检索相同的常量时,却没有定义


const weekday=document.querySelector('.weekday');
常日=[‘星期一’、‘星期二’、‘星期三’、‘星期四’、‘星期五’、‘星期六’、‘星期日’];
设置间隔(()=>{
const d=新日期();
const day=days[d.getDay()];
异步函数showtime(){
等待天气预报();
console.log(日出时间);//返回未定义的
console.log(day)//日志正常,周三返回。
weekday.innerHTML=天+',日出时间:'+日出时间;
}
showtime();
}, 1000);
// 
const openweather_api=”https://api.openweathermap.org/exampleexample";
异步函数getWeather(){
console.log('先运行天气函数')
const response=wait fetch(openweather_api);
const json=await response.json();
const sunristime=`${json.sys.sunrise}`//以秒为单位记录日出时间。
}
getWeather();//运行良好,并从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中有关变量提升的更多信息

Just
return
函数中的值,并将其分配给调用范围内的局部变量。将其更改为作用域,感谢您让我注意到

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);

}