是否可以在异步函数上执行FOR循环?

时间:2017-07-08 21:24:18

标签: javascript node.js rest loops asynchronous

我想找到一种方法在下面的代码上执行 FOR 循环,以便一次向不同的主机发送多个请求,并通过“<”的功能将它们分离为HTML。 EM> handleLedResponses ”。

下面的代码在单个主机的用例中运行良好,但是当我尝试通过FOR循环发送多个请求时,由于异步问题而无法通过数组调用每个主机。

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;
        }
    }
}

下面的代码是带有FOR循环的代码,我添加了一个问题,将 hostIndx2 的变量传递给handleLedResponses2的渲染函数,因为承诺问题 -

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;
    }
}

0 个答案:

没有答案