为了账号安全,请及时绑定邮箱和手机立即绑定

如何将此代码转换为 async wait 语法?(反应本机)

如何将此代码转换为 async wait 语法?(反应本机)

宝慕林4294392 2023-12-14 16:55:19
我正在尝试通过尝试将此代码转换为它来学习如何使用异步等待。有人可以指导我完成它吗?const fetchWeather = () => {    fetch(      "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***"    )      .then((res) => res.json())      .then((json) => {        setData({ data: json });        setTemp({ temp: (json.main.temp - 273.15).toFixed(2) + " C" });        setCityDisplay({ cityDisplay: json.name });        setIcon({ icon: json.weather[0].icon });        setMain({ main: json.weather[0].main });        setHumidity({ humidity: json.main.humidity + " %" });        setPressure({ pressure: json.main.pressure + " hPa" });        setVisibility({          visibility: (json.visibility / 1000).toFixed(2) + " km",        });      })      .catch((err) => console.warn(err));  };到目前为止我有这个:async function fetchWeatherr() {    try {      const response = (        await fetch(          "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***"        )      ).json();    } catch (err) {      console.warn("error");    }  }但我不确定是否应该使用像 useEffect 这样的钩子
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

你可以这样做


async function fetchWeatherr() {

  try {

    const response = await fetch(

      'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***'

    );

    const json = await response.json();

    setData({ data: json });

    setTemp({ temp: (json.main.temp - 273.15).toFixed(2) + ' C' });

    setCityDisplay({ cityDisplay: json.name });

    setIcon({ icon: json.weather[0].icon });

    setMain({ main: json.weather[0].main });

    setHumidity({ humidity: json.main.humidity + ' %' });

    setPressure({ pressure: json.main.pressure + ' hPa' });

    setVisibility({

      visibility: (json.visibility / 1000).toFixed(2) + ' km',

    });

  } catch (err) {

    console.warn('error');

  }

}


查看完整回答
反对 回复 2023-12-14
  • 1 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信