0

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;
Navitas28
  • 745
  • 4
  • 13
luke jon
  • 201
  • 2
  • 10
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ggorlen Aug 13 '20 at 04:39
  • I am seeing the following when I look at the logs.TypeError: apiRequest.end is not a function but I dont understand why, will have a read through the doc. Thanks – luke jon Aug 13 '20 at 04:43

1 Answers1

1

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)
    }
Navitas28
  • 745
  • 4
  • 13