在 JavaScript 中使用 fetch 时如何显示和隐藏 loader?

How to show and hide loader while using fetch in JavaScript?

我正在使用 JavaScript Fetch 来访问 API,并且我想在获取过程中显示加载程序。我正在使用以下代码...

      async function fetchStates() {
            showLoader();
            await fetch('https://localhost:7123/locations/states?token=@{@HttpContext.Session.GetString("sessionToken")}')
            .then(response => response.json())
            .then(states => {
                for (let i = 0;i < states.length;i++){
                    let option = document.createElement('option');
                    option.text = states[i].name;
                    option.value = states[i].id;
                    ddlCAStates.appendChild(option)
                }
                /*hideLoader(1);
                scrollToTop(1);*/
            })
            .catch(error => {
                divErrors.style.display = "block";
                let errorName = GetHttpErrorName(error.toString());
    
                txtErrors.textContent = 'The server responded with error: ' + error + ' ' + errorName;
                /*hideLoader(2);
                scrollToTop(2);*/
            })
            .finally(() => {
                hideLoader();
                scrollToTop();
            });
        }

    function showLoader() {
        document.getElementById('loader').style.display = 'block';
    }

    function hideLoader() {
        document.getElementById('loader').style.display = 'none';
    }

    function scrollToTop() {
        document.body.scrollTop = 0; // For Safari
        document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    }

加载程序显示一瞬间,然后在获取完成之前隐藏。加载程序应该是可见的,直到提取成功加载数据或由于任何原因失败。我在这里做错了什么?

使用 try-catch-finally 和 async/await

async function fetchStates() {
      showLoader();
      try{
       console.log("fetching starts");
       const res = await mock();
       const states = await res.json();
       console.log("fetching completes");
       console.log("states:", states);
      }catch(error){
        console.log(error.toString());
      }finally{
        hideLoader();
      }
  }
 function mock(){ return new Promise(resolve => setTimeout(() => resolve({ json:() =>  Promise.resolve([1,2,3]) }), 2000)) }
 function showLoader(){ console.log("loader showes") }
 function hideLoader(){ console.log("loader hides") }
 
fetchStates();