I am building an api that receives an array of items then calls a function passing the array as a parameter.
router.post('/api/statuses/:client', function (req, res, next) {
console.group('FETCHING STATUS CALLS')
console.log(`In POST /api/statuses/${req.params.client}`);
let apps = new Array(); //req.query.app ? req.query.app : apps
if (req.query.app){
apps.push(app)
} else {
apps = ['xyz', 'abc', 'def']
}
const env = req.query.env ? req.query.env : 'int'
getParentApp(apps, env, res)
console.groupEnd('FETCHING STATUS CALLS')
});
In the getParentApp, I mapped the array and for each item in the aforementioned array, I did a fetch call to receive the information from an API that returns an Object.
function getParentApp(apps, env, res) {
let hashes = new Array();
let parent;
let id = '';
let pass = ""
console.group('GETTING PARENT')
apps.map(app => {
layer = app.charAt(0)
appName = app.slice(1)
console.log(appName, env.toLowerCase(), parent)
fetch(`https://${env}.api.com/${app}/v1/status?layerOption=${layer}api`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + base64.encode(`${id}:${pass}`)
}
}).then(res => res.json())
.then(data => {
return data
}).then(data => hashes.push(data)) // If I change this to a console.log, it returns the expected data.
.catch((err) => {
console.log(err)
})
console.log(hashes)
})
console.log(hashes)
console.groupEnd('GETTING PARENT')
}
I tried placing the fetch call in a separate function, which helped to return an object but rather than pushing the next fetch calls' response into the array, it attempts to overwrite it. What am I doing wrong here? Async functions did not work for me, maybe I'm misusing them?