Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

I'm using JavaScript Fetch to access an API and I want to show a loader while the fetch is in progress. I'm using the following code...

      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
    }

The loader displays for a split second and then hides way before the fetch is completed. The loader should be visible until either the fetch successfully loads data or it fails for any reason. What I'm doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use try-catch-finally with 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();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!