如何一个接一个地运行相同的承诺NodeJs

时间:2017-06-21 11:46:13

标签: node.js ecmascript-6 promise request es6-promise

我正在尝试解决以下问题。 考虑以下情况。我需要检查一组服务器是否还活着。或者更具体地说,我需要从提供的列表中找到第一个工作服务器,我需要逐个完成。

例如,如果第一台服务器不起作用,请检查另一台服务器......

至于NodeJS是异步的,我不能在for循环中执行此操作。所以我尝试实现类似于递归的东西,它看起来很丑陋并且不起作用,但我已经尝试过了)

 static findWorkingServer(servers, payload) {
        return NetworkUtils.getMyPublicIP()
            .then((ip) => {
                return new Promise(function (resolve, reject) {
                    let currentIndex = -1;
                    if (servers.length > 0) {
                        let currentServer;
                        let serverCheckCallback = function (result) {
                            if (result) {
                                resolve({working: currentServer, payload: payload});
                            }
                            else {
                                if (currentIndex < servers.length-1) {
                                    currentIndex++;
                                    currentServer = servers[currentIndex];
                                    NetworkUtils.checkIfServerWorking(currentServer, ip)
                                        .then(serverCheckCallback);
                                }
                                else {
                                    reject(new Error("No working servers found"))
                                }
                            }
                        };
                        serverCheckCallback(false);
                    }
                    else {
                        resolve(new Error("No servers provided"));
                    }
                })
            });
    }
static checkIfServerWorking(credentials, publicIp) {
    return new Promise(function (resolve, reject) {
        if(credentials) {
            request({
                url: credentials.url,

                agentClass: agentClass,
                agentOptions: {
                   // Agent credentials
                }
            })
                .then(res => {
                     // Do some stuff with resposne
                    resolve(someCondition);
                })
                .catch(err => {
                    resolve(false);
                });
        }else {
            resolve(false);
        }
    });
}

请帮助获得所需的结果,也许可以同步运行请求。

1 个答案:

答案 0 :(得分:0)

可以使用await / async:

完成

let servers = ["test0.com","test1.com","test2.com","test3.com","test4.com"]

class ServerTest {
    static async checkServer(name) {
        if (name === "test3.com") 
            return true //returns promise that resolves with true
        else
            return false //returns promise that resolves with false
    }
}

(async()=>{ //IIFE (await can only be used in async functions)
    let targetServer
    for (i in servers) {
        if (await ServerTest.checkServer(servers[i]) === true) {
            targetServer = servers[i]
            break
        }
    }
    console.log("Found a working server: " + targetServer)
})()