0

I have a database with cars and a 3rd party api where I can update some info about them. I have written this code in order to update every x days, but the problem is that the 3rd party database doesn't allow more than x connections per hour. So what I want to do is a function that does one request sequentially every 40s

My database looks like

[{id: 1, name: "car1", rating: 4.6, external_db_id: 12342}, 
 {id: 2, name: "car2", rating: 4.7, external_db_id: 99999}]

Updated code:

async () => {

  const allCars = await functionThatGetsCars()


  for ( var i = 0; i < allCars.length; i++ ) {
    let car = allCars[i]
    let canUpdate = null

    try{
      canUpdate = await fetchExternalData(car.external_db_id)
    } catch(err){
      console.log("Error fetching external data", err)
      canUpdate = null
    }

    if(canUpdate){
      await new Promise((resolve, reject) => setTimeout(resolve, 40000))

      const updated =  await functionThatUpdatesCarsInMyDB({
        id: car.id,
      },
      {
        rating: canUpdate ? canUpdate.external_rating : car.rating
      }

      return updated
    }
  }
}

Problem is that right now that it does just update the first item from the loop. What would be the way to make it sequentially with a timeout of 40s? Thanks in advance!

Joe82
  • 1,357
  • 2
  • 24
  • 40
  • 3
    Just use a `for` loop and `await` every element in that loop. In each iteration you can check the elapsed time. *edit:* Or I guess you can just put the "timeout" in each iteration of the loop, just like you have it now. – Felix Kling Jun 10 '21 at 09:56
  • 1
    @FelixKling also probably useful `await new Promise(resolve => setTimeout(resolve, 40000))` – VLAZ Jun 10 '21 at 09:57
  • @VLAZ: Yeah, I only read the bottom part of the question :-/ – Felix Kling Jun 10 '21 at 09:58
  • Updated the code with @FelixKling suggestion, now the problem is that it just updates the first item. – Joe82 Jun 10 '21 at 10:26
  • 1
    Because you have `return updated` in your loop. That will of course terminate the function (and the loop). No idea what you expect this function to return. – Felix Kling Jun 10 '21 at 10:52
  • True that (it was a leftover from the old code) – Joe82 Jun 10 '21 at 11:01

1 Answers1

0

Solved thanks to @FelixKling suggestions:

async () => {

  const allCars = await functionThatGetsCars()


  for ( var i = 0; i < allCars.length; i++ ) {
    let car = allCars[i]
    let canUpdate = null

    try{
      canUpdate = await fetchExternalData(car.external_db_id)
    } catch(err){
      console.log("Error fetching external data", err)
      canUpdate = null
    }

    if(canUpdate){
      await new Promise((resolve, reject) => setTimeout(resolve, 40000))

      const updated =  await functionThatUpdatesCarsInMyDB({
        id: car.id,
      },
      {
        rating: canUpdate ? canUpdate.external_rating : car.rating
      }

    }
  }
}
Joe82
  • 1,357
  • 2
  • 24
  • 40