Using axios to call an API, and running calls in a loop to fetch data from response - Traversing through a tree of elements (I'm trying to fetch Element-IDs) I suspect (but obv not sure), by the time API returns a response, the loop ends and array doesn't get populated. It is a nested structure of loops.
I'd really appreciate if someone could help please.
Code snippet:
async function callTheApi(assetId) {
const baseURL = process.env.API_ENDPOINT;
const endpointVersionUrl = 'some_endpoint';
const endpointUrl = `/endpointA/${assetId}/endpointB`;
const config = {
headers: { Authorization: `Bearer ${process.env.AUTH_TOKEN}` },
};
const response = await axios.get(
`${baseURL}${endpointVersionUrl}${endpointUrl}`,
config,
);
return response;
}
async function fetchAllChildrenAssetId(assetId) {
const response = await callTheApi(assetId); //returns an array of objects
const responseALLChildArray = response.data;
console.log(responseALLChildArray);
let allChildrenAssetArray = [];
let sizeOfTempArrayIsNotZero = true;
let immediateChildArray = [];
responseALLChildArray.forEach((element) => {
allChildrenAssetArray.push(element.minor_id);
immediateChildArray.push(element.minor_id);
});
while (sizeOfTempArrayIsNotZero) {
let tempChildArray = [];
immediateChildArray.forEach(async (element) => {
const response = await callTheApi(element); //returns an array of objects
const res = response.data;
res.forEach((element) => {
allChildrenAssetArray[allChildrenAssetArray.length] = element.minor_id;
tempChildArray[tempChildArray.length] = element.minor_id;
});
});
immediateChildArray = [];
immediateChildArray = tempChildArray;
if (tempChildArray.length === 0) {
sizeOfTempArrayIsNotZero = false;
}
}
console.log(allChildrenAssetArray);
return allChildrenAssetArray;