Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda