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

222
Vistas
How to sleep between each axios call in react

I'm writing an app that needs to query an RestAPI with a set of input. However, that API is very bad at scaling and it will return code 429 if it receives too many request. So I was trying to add a sleep function between each axios call but it seems not working. Wondering if I have this sleep function set correctly.

const sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}


useEffect(() => {
    let results = [];
    
    async function fetchData(id) {
        let request = someAPI + id + query;
        axios.get(request).then((result) => {
            results.push(result);
        }).catch((error) => {console.log(error);});
        await sleep(2000);
    }

    for (let i = 1; i <= 20; i++) {
        fetchData(i);
    }
    
},[]);

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You didn't await the fetchData function, you can try this.

useEffect(() => {
  let results = [];

  async function fetchData(id) {
    try {
       const result = await axios.get('')
       results.push(result);
       await sleep(2000)
    }
    catch(error) {
       console.log(error);
    }
  }

 (async function() {
   for (let i = 1; i <= 20; i++) {
     await fetchData(i);
   }
 })()


},[]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

In your for loop, you have to await the fetchData function. This way, for each iteration, the process will wait for fetchData (and therefore the nested call to the sleep function) to complete.

Currently, you're just firing off all 20 calls to fetchData at once, without actually waiting for your sleep function.

async function fetchAll() {
  for (let i = 0; i < 20; i++) {
    await fetchData()
  }
}

fetchAll()

Note that you will have to wrap your for-loop in an async function, in order to be able to use await within the loop.

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