Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

494
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda