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!