Reputation: 201
I want to loop through my array and post API calls each time to create a new record for each value in the array.
The below example would have made 3 separate calls and returned 3 new records but I can't get it to work, can someone advise if this is even the best method ?
var tens = "boo, foo, bar";
var letters = tens.split(',').map(string=>string.trim());
const apiCalls = callAPIs(letters);
function callAPIs(letters) {
responses = [];
letters.forEach(group => {
var apiRequest = http.request({
'endpoint': 'site',
'path':'/api/v1/table/incident',
'method': 'POST',
"headers": {
"Authorization": "Basic xxxxxxxxxxxxx=",
"Content-Type": "application/json"
}
})
apiRequest.write(group)
apiRequest.end((data) => {
responses.push(data)
});
});
return responses
console.log(responses)
}
var data = {};
var caller_id = "user1";
data.caller_id = caller_id;
Upvotes: 0
Views: 662
Reputation: 777
Firstly you need to understand forEach
in js
is not promise aware. You have to use the old school for
loop or some iterable for...in
async function callAPIs(letters) {
responses = [];
for (const i = 0; i < letters.length; i++) {
var apiRequest = await http.request({
'endpoint': 'site',
'path': '/api/v1/table/incident',
'method': 'POST',
"headers": {
"Authorization": "Basic xxxxxxxxxxxxx=",
"Content-Type": "application/json"
}
})
apiRequest.write(group)
apiRequest.end((data) => {
responses.push(data)
});
});
return responses
console.log(responses)
}
Upvotes: 1