So im trying to make a request to an API using a foreach loop on an array. The array contains a list of strings that are placed into the request
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("", "");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
var array = [];
var data = [];
var importdata = new Promise((resolve, reject) => {
$.getJSON('name of json.json')
.then(response => {
data = response;
resolve(response)
})
.catch(err => {
reject(err)
})
})
var getAPIResults = new Promise((resolve, reject) => {
var xmlHttp = new XMLHttpRequest();
data.forEach((element) => {
console.log(element) // This isn't being outputted into the console, even though 'data' array has elements after running 'importdata'
xmlHttp.open( "GET", 'http://api.com/json/apiroute?key=xxxx-xxx-xxxx&dataitem='+element, true );
xmlHttp.send( null );
array.push(xmlHttp.responseText)
})
resolve(xmlHttp.responseText)
})
async function main () {
await importdata
await console.log(data)
await console.log(getAPIResults)
}
main()
I have added a comment where the data isn't being logged
Here is what the console looks like:
{Data: {…}}
Data:
data: (1030) [expected data elements]
__proto__: Object
__proto__: Object
Promise {<fulfilled>: ""}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: ""
Surely there should be a long list of elements (the data
array is around 1000 elements long) when getAPIResults
is ran?