I'm trying to build webpage with car database API (just for school purposes) and I'm stuck on this point. I want to request untill all cars will be found (I need to do this in loop cause this API allow to request only 50 cars at once). In this case loop will be sending requests untill number of results will be less than 50 (max) but I can't grab value of response.data.length and use it in while(). Is there any method to do this?
My code:
do {
const options = {
method: 'GET',
url: 'https://car-data.p.rapidapi.com/cars',
params: {
limit: '50',
page: '$output_page',
year: input_year,
make: input_brand,
type: input_type
},
headers: {
'x-rapidapi-host': 'car-data.p.rapidapi.com',
'x-rapidapi-key': '*KEY*'
}
};
await sleep(2000);
lengthVar = axios.request(options).then(function(response) {
console.log(response.data);
return response.data.length;
}).catch(function (error) {
console.error(error);
return error;
});
}while((lengthVar % 50) == 0);
The problem is that the while loop does not wait for the call to finish, so by the time even the first call returns the while loop has already ran bazillion times.
You can resolve this by having a recursive function that makes another call after the results return only if the length is 50.
This way every new call is only triggered after the previous one has returned and you have the data and its length.
function requestData() {
const options = {
method: 'GET',
url: 'https://car-data.p.rapidapi.com/cars',
params: {
limit: '50',
page: '$output_page',
year: input_year,
make: input_brand,
type: input_type
},
headers: {
'x-rapidapi-host': 'car-data.p.rapidapi.com',
'x-rapidapi-key': '*KEY*'
}
};
axios.request(options).then(function(response) {
console.log(response.data);
if (response.data.length === 50) {
requestData()
}
}).catch(function (error) {
console.error(error);
return error;
});
}
requestData()