我正在尝试通过 Javascript 检索事件主机列表。该功能应按如下方式实现:
//getState returns an array of states (up or down) for all the given list of ip addresses
var host_states = getState(list_of_ip_addresses);
为了检查主机是否存在,我正在使用 websockets:
var ip = "ws://"+current_ip;
var s = new WebSocket(ip);
//if the onerror is called, state host as up
s.onerror= function(){/*state host as up*/};
//after a delay, automatically state host as down
setTimeout(function(){/*state host as down*/},delay);
由于主机的状态是通过回调(异步)确定的,我该如何返回一个或多个主机的状态,就像在上面的函数中一样? (无轮询)
最佳答案
您可以使用 Promises 一次异步返回所有主机。
async function getStates(l) {
let promises = [];
for(let i in l) {
let current_ip = l[i];
promises.push(new Promise((resolve, reject) => {
let delay = 10;
var ip = "ws://"+current_ip;
var s = new WebSocket(ip);
//if the onerror is called, state host as up
s.onerror= function(){/*state host as up*/resolve(true)};
//after a delay, automatically state host as down
setTimeout(function(){/*state host as down*/resolve(false)},delay);
}));
};
console.log(promises);
const results = await Promise.all(promises);
return results;
}
getStates([1,2,3]).then(r => console.log(r));
关于javascript - 返回具有异步功能的事件主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904423/