I want to find a way to perform FOR loop on the code below for send a multiple request to a different hosts in one shot and render them in separated to the HTML by the function of "handleLedResponses".
The code below works fine in use case of a single host but when I've tried to send a multiple requests by FOR loop that call to each host by array it doesn't work because an async problems.
var fetch = require('node-fetch');
function collectionChecking() {
const ledTypesA = {
green: "<img id='logo' src='green.png' height='30' width='30'>",
red: "<img id='logo' src='red.png' height='30' width='30'>",
yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};
let token = '111111111';
let url = 'http://host1.com:8000/api';
fetch(url, {method: 'GET', headers: {"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}
).then(function (res) {
console.log(res.status);
handleLedResponse(res);
});
function handleLedResponse(res) {
var curSpan = document.getElementById('col_host_0');
if (res.status === 200 || res.status === 204) {
curSpan.innerHTML = ledTypes.green;
} else if (res.status === 500 || res.status === 404) {
curSpan.innerHTML = ledTypes.red;
} else if (res.status === 300 || res.status === 301 || res.status === 302) {
curSpan.innerHTML = ledTypes.yellow;
}
}
}
The code below is the code with the FOR loop that I've add a problem to pass the variable of hostIndx2 to the rendering function of handleLedResponses2 because the promise issues -
var fetch = require('node-fetch');
var ledTypes = {
green: "<img id='logo' src='green.png' height='30' width='30'>",
red: "<img id='logo' src='red.png' height='30' width='30'>",
yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};
var hosts2 = ['http://host1.com','host2.com','host3.com','host4.com'];
var hostIndx2 = 0;
var lengthVal = hosts2.length;
var token = '1213232431';
function collectionChecking() {
console.log("im inside the func" + hostIndx2 + "---" + lengthVal);
for (; hostIndx2 < lengthVal; hostIndx2++) {
console.log(hostIndx2);
let url = hosts2[hostIndx2];
// sendReq();
fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}
).then(function (res, hostIndx2) {
console.log(res.status, hostIndx2);
handleLedResponse2(res, hostIndx2);
});
}
}
function handleLedResponse2(res, hostIndx2) {
var curSpan = document.getElementById('col_host_' + hostIndx2);
console.log("IM HERE" + res.status + "---" + hostIndx2);
if (res.status === 200 || res.status === 204) {
curSpan.innerHTML = ledTypes.green;
} else if (res.status === 500 || res.status === 404) {
curSpan.innerHTML = ledTypes.red;
} else if (res.status === 300 || res.status === 301 || res.status === 302) {
curSpan.innerHTML = ledTypes.yellow;
}
}