im trying to make a function and pass a url to it and return the url data in json or array. when i call the function i get a empty array first then it will be filled. there is a small delay is guess. i cant iterate between the data and cant use the data cuz the array is empty at that moment. here is the function:
function fetch_api(url){
const data = new Array();
const getproducts = new XMLHttpRequest();
getproducts.open('GET',url);
getproducts.send();
getproducts.onload = function(){
if(getproducts.status == 200){
data.push(JSON.parse(getproducts.responseText));
}else{
throw new Error('fetching api failed!');
}
}
return data;
}
and
const data = fetch_api(all_products_api);
console.log(data);
result: ScreenShot