0

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);
    }
    
},[]);
  • What about using an async for loop and putting the sleep after `fetchData`? https://stackoverflow.com/a/56798334/989920 – evolutionxbox Jul 04 '22 at 09:45

2 Answers2

1

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);
   }
 })()


},[]);
Mina
  • 14,386
  • 3
  • 13
  • 26
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.

robng
  • 38
  • 7