'Time promise requests to an API using setInterval or setTimeout
I have this issue - I'm trying to fetch a data from a constant url that accepts an integer ID.
I have these integers stacked in array. I do not want to flood the server with requests so I tried using setInterval and setTimeout to time the requests.
I did take in consideration that a promise might take some time to complete but couldn't figure out how to explicitly apply that.
The results of this code are just: "[] 1"
const axios = require('axios')
const dataFile = require('../data/car_data')
const modelNameUrl = 'https://www.gov.il/api/mot/carlistprice/api/modelName?yazran_id='
const carId = dataFile.map(data => data.manufacturer_id)
const fetch = async (id) => {
const dataFetched = await axios.get(`${modelNameUrl}${id}`).then()
return dataFetched.data.dgamim_yazran
}
let index = 0
setInterval(async () => {
const data = await fetch(index)
index++
console.log(data, index)
}, 10000)
Additional code for further debugging:
const axios = require('axios')
// const dataFile = require('../data/car_data')
// dataFile.map(data => data.manufacturer_id)
const modelNameUrl = 'https://www.gov.il/api/mot/carlistprice/api/modelName?yazran_id='
let dataArray = []
const fetch = async (id) => {
const dataFetched = await axios.get(`${modelNameUrl}${id}`)
return dataFetched.data.dgamim_yazran
}
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
let integerSource = [
6, 67, 4, 5, 9, 60, 7, 30, 107, 113, 19,
120, 15, 17, 12, 59, 3, 129, 56, 1, 124, 29,
26, 64, 33, 63, 131, 112, 2, 39, 133, 38, 40,
48, 52, 53, 54, 50, 13, 110, 51, 57, 68, 23,
44, 22, 41, 21, 10, 32, 47, 45, 11
]
async function runLoop() {
for (let index of integerSource) {
try {
const data = await fetch(index);
console.log(data, index);
await delay(5000);
} catch (e) {
console.log(`Error on index ${index}`, e);
throw new Error
}
}
}
runLoop().then(() => {
console.log("all done");
}).catch(err => {
console.log("ended with error\n", err);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
