首页 > 解决方案 > 如何在原生 JavaScript 中异步管理状态

问题描述

我正在获取数据

 const getAllCountries = async () => {
    try {
      const response = await axios.get(`/api/cities-list`);
      return response.data;
    } catch (err) {
      return err.response;
    }
  }

 const allCountries = await getAllCountries();

使用 vanilla JS,我想为较慢的连接添加某种加载状态(或者如果 api 需要比正常时间更长的时间来响应)。我正在这样做

 const getAllCountries = async () => {
    try {
      document.querySelector('#results').innerHTML = 'Loading'; // Displaying 'Loading' text
      const response = await axios.get(`/api/cities-list`);
      document.querySelector('#results').innerHTML = null;
      return response.data;
    } catch (err) {
      return err.response;
    }
  }

 const allCountries = await getAllCountries();

这在慢速连接上工作正常,但在较快的连接上,“加载”文本会出现一瞬间,然后消失,这是预期的。

如何添加某种延迟(例如setTimeout)以使加载状态仅在 1 秒后显示(例如)?如果在 1 秒之前返回数据,则不显示加载状态。换句话说,快速连接的用户将看不到加载文本。

标签: javascriptasync-awaitaxios

解决方案


如果您response在范围内提升得更高,您可以在超时内访问它

const getAllCountries = async () => {

    try {
      let response;

      setTimeout(() => {
        if (!response) {
          document.querySelector('#results').innerHTML = 'Loading'; // Displaying 'Loading' text
        }
      }, 1000)
      
      response = await axios.get(`/api/cities-list`);
      document.querySelector('#results').innerHTML = null;
      return response.data;
    } catch (err) {
      return err.response;
    }
  }

推荐阅读