0

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;
    }
}
Idan E
  • 1,299
  • 4
  • 17
  • 42
  • 1
    Check out `Promise.all` – Balázs Édes Jul 08 '17 at 21:26
  • 1
    Show us what you tried with the for loop – Steven Wexler Jul 08 '17 at 21:27
  • Are you trying to call `collectionChecking()` or the `fetch()` in a loop? Post an example of what you've tried so far so we can help. – Cisco Jul 08 '17 at 21:28
  • https://stackoverflow.com/questions/44636542/loop-through-asynchronous-request/44636736#44636736. Check out aysnc API from node – Arpit Solanki Jul 08 '17 at 21:29
  • This is perfect code to send multiple requests and use callback to handle there responses. What exactly is the problem you are facing? – Zeeshan Jul 08 '17 at 21:31
  • what asycn problem? Please describe your problem as well. What error are you getting in console or network tab? – Zeeshan Jul 08 '17 at 21:32
  • Thank you all for the comments, i've added my problematic code with the FOR loop above – Idan E Jul 08 '17 at 21:39
  • The value of `hostIndx2` will have reached its maximum value before any of the `fetch` callbacks are executed, and so `hostIndx2` will not be what you want it to be. Simple solution: use `let`: `for (let hostIndx2 = 0; hostIndx2 < lengthVal; hostIndx2++)` – trincot Jul 08 '17 at 21:46
  • Thanks, but how can I pass the value of hostIndx2 from the function of collectionChecking to the next function of hanleLedResponses? @trincot – Idan E Jul 09 '17 at 07:23
  • That can stay as it is when you use `let` for your `for` loop variable so that it becomes a separate variable in each iteration. Just pass it. – trincot Jul 09 '17 at 08:12
  • OK, thanks. and how can I handle with to pass more than one argument inside the "then" function for to pass "res" and "hostIndx2" as well? @trincot – Idan E Jul 09 '17 at 10:32
  • You can pass more arguments to the `then` callback (or any function) by using `bind`. For instance: `then(function (hostIndx2, res) { ... }.bind(null, hostIndx2))`. Make sure `hostIndx2` is the first argument. But you could just leave out the `hostIndx2` parameter, and reference the original `hostIndex2` loop variable. – trincot Jul 09 '17 at 12:54

0 Answers0