javascript - 使用异步函数返回活动主机
问题描述
我正在尝试通过 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));
推荐阅读
- linq - LINQ:向上遍历层次结构以检索父层次结构
- windows - 启动时的 Websocket 连接 ssl 问题(Windows)
- sql - 3 Table SQL JOIN with CASE
- android - RecycleView 中多视图类型的 Mutli LiveData 对象
- python - 混淆矩阵的图看起来很奇怪
- python - Glitch.com 与 Python
- assembly - 从 xml 文件中提取有用的信息。这些xml文件是制造商用来更新MCU的吗?
- azure-data-explorer - How to find an item in a json array using kusto
- javascript - 使用列表项的树视图,但单击事件不适用于动态创建的 HTML 内容
- typescript - 将新元素添加到数组时,使用 trackBy 嵌套 NgFor 不更新 html