ECMAScript 6 - Loop through array to make API POST calls

Viewed 80

I have an input in the format "ABC, DGE, GHI, ...."

I want to convert this comma-separated list into an array and then call my API to do a POST request for each value in the array. Can anyone give me a pointer on the best method?

Example

Call 1 POST data "caller" tens=ABC
Call 2 POST data "caller" tens=DFE
Call 3 POST data "caller" tens=GHI

working idea

var tens = "ABC, DEF, GHI";
var letters = tens.split(',');
const Array = callAPIs(letters) 

var data = {};

var caller_id = "caller";
data.caller_id = caller_id;

function callAPIs(letters) {
  var Array = [];
  for (let i = 0; i < letters.length; i++) {
   var apiRequest = http.request({
    'endpoint': 'http://xxxxxxxxxxxxxxxxxxxxxxx',
    'path':'/api/v1/table/record', 
    'method': 'POST',
    "headers": {
    "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxx=",
    "Content-Type": "application/json"
    }
    }); 
1 Answers

Is something like this what you expect?

var tens = "ABC, DEF, GHI"
var letters = tens.split(',').map(string=>string.trim())
const apiCalls = callAPIs(letters) 

function callAPIs(letters) {
  responses = []

  letters.forEach(group => {
    var apiRequest = http.request({
      'endpoint': 'http://xxxxxxxxxxxxxxxxxxxxxxx',
      'path':'/api/v1/table/record', 
      'method': 'POST',
      "headers": {
        "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxx=",
        "Content-Type": "application/json"
      }
    })
    apiRequest.write(group)
    apiRequest.end((data) => {
      responses.push(data)
    })
  })
  
  return responses
}
Related