0

I am trying to run the below script to call my api 3 times (looping through the array) and creating a new record using POST method. I can't see in my logs the api call is even been initiated. Can anyone see where I am going wrong?

var tens = "rec1, rec2, re3"
console.log(tens);

var letters = tens.split(',').map(string=>string.trim());
console.log(letters);

async function callAPIs(letters) {
    responses = [];
    for (let i = 0; i < letters.length; i++) {
        var apiRequest = await http.request({
            'endpoint': 'test',
            'path':'/api/table/records', 
            'method': 'POST',
            "headers": {
                "Authorization": "Basic xxxxxxxxx=",
                "Content-Type": "application/json"
            }
        })
        apiRequest.send(data)
        apiRequest.end((data) => {
            responses.push(data)
        });
    };
    return responses
 }

var data = {};    
var caller_id = "user1";
data.caller_id = caller_id;
console.log(caller_id);
luke jon
  • 201
  • 2
  • 10
  • A `console.log` *after* a `return` statement will never get executed. You also never do anything with `apiCalls`? The last 4 lines of your code seem unrelated to anything else in your code. – trincot Aug 13 '20 at 06:13
  • The last 4 lines is the data I am sending in the post request. - Amended, I had some code carried over. – luke jon Aug 13 '20 at 06:20
  • 1
    You are awaiting for a post without any data posted and then write a data to that post, I don't think that's what you are trying to do. What is `group`? Seems to be undefined from your code. Anyway you should make it on callbacks, not await. – Flash Thunder Aug 13 '20 at 06:27
  • 2
    `await http.request` .... unless `http.request` returns a Promise, `await` here does nothing - hint, `http.request` immediately returns `http.ClientRequest` - which you subsequently use, so you know what it's returning - so, `await` is doing absolutely nothing in your code – Jaromanda X Aug 13 '20 at 07:07
  • I was just reading about promises and wondering if that's what I am missing or can I get away without them? The async and await is confusing me, more reading. Thanks – luke jon Aug 13 '20 at 07:53
  • check that out, should help: https://stackoverflow.com/questions/38362231/how-to-use-promise-in-foreach-loop-of-array-to-populate-an-object – Flash Thunder Aug 13 '20 at 10:00

0 Answers0