I am new to Node JS and I'm struggling to understand how to run a for loop inside an asynchronous function. There is another async function inside the for loop.
I should be getting a response of some values in promArray. However, I am getting an empty array.
const rp = require('request-promise');
const options2 = {
uri: 'uri',
method: 'GET',
auth: {
'user': 'username',
'pass': 'password'
}
};
var promArray = [];
function executeMethod() {
rp(options2).then(function(body) {
const jsonData = JSON.parse(body).result;
// iterate through the pods
jsonData.forEach(element => {
promArray.push(getProjectName(element.u_hig_proj_name.value))
});
});
return Promise.all(promArray);
}
function getProjectName(projectSysId) {
const projectTableAttrbutes = {
uri: 'uri',
method: 'GET',
auth: {
'user': 'username',
'pass': 'password'
}
};
return new Promise(function(res, rej) {
// call the project table
rp(projectTableAttrbutes).then(function(body) {
//console.log(JSON.parse(body).result.name);
res(JSON.parse(body).result.name);
})
})
}
// final execution
executeMethod().then(function(done) {
console.log(done);
});