I want to access some data from an API and ran into a problem. My code is fetching some data from the API, will compare it with a local copy of an API. I want it to store some data in an array if the local copy does not match the copy fetched from the API. The fetching and comparison is working fine. The problem comes up when I try to fill the array and want to give it back. The request
function is async so my return value at the end will be undefined. My function checkForDiff
should return this array after the for-loop is done, because after the foor-loop the array should be filled with the information I need. I am a newbie in Nodejs so I really do not know how to fix it. I need the array to be filled before returning it, but the async request
call is causing me problems. How can I achieve this kind of behavior?
Thank you for your help in advance
function checkForDiff(){
let outdatedLanguages = [];
var options = {
url: 'https://xxxxxxxxxxxxxxxxxxxxxxxxx',
headers: {'Key': 'xxxxxxxxxxxxxxxxxxxxxx'}
};
for(let index = 0; index < locales.length; index++){
//Change url for new https request
options.url = `https://xxxxxxx?locale=${locales[index].symbol}`
//Send new https request to API
request(options, (error, response, body)=>{
var localState = hash(JSON.parse(filesystem.readFileSync(`./cards/cards-${locales[index].symbol}.json`)));
var recentState = hash(JSON.parse(body));
/If the local card base is not up to date, add locale to array
if(localState !== recentState){
outdatedLanguages.push(locales[index].symbol);
}
);
}
//Return outdatedLanguages array
return outdatedLanguages;
}