如何一个接一个地运行相同的 Promise NodeJs
Posted
技术标签:
【中文标题】如何一个接一个地运行相同的 Promise NodeJs【英文标题】:How to run same promises one after another NodeJs 【发布时间】:2017-11-24 07:16:56 【问题描述】:我正在尝试解决以下问题。 考虑以下情况。我需要检查一组服务器是否还活着。或者更具体地说,我需要从提供的列表中找到第一个工作服务器,我需要一个一个地执行此操作。
例如,如果第一个服务器不工作,检查另一个和另一个...
就 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);
);
请帮助获得想要的结果,也许可以同步运行请求。
【问题讨论】:
试试这个.....github.com/caolan/async 【参考方案1】:可以用 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)
)()
【讨论】:
感谢您的回答,但正如您所见,我使用的是静态方法,我尝试过,但它不起作用 这应该不是问题。只需让它们也异步。以上是关于如何一个接一个地运行相同的 Promise NodeJs的主要内容,如果未能解决你的问题,请参考以下文章
我如何确保Producer和Consumer线程一个接一个地无限运行?