首页 > 解决方案 > 使用异步函数返回活动主机

问题描述

我正在尝试通过 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);

由于主机的状态是通过回调(异步)确定的,我如何返回一个或多个主机的状态,就像上面的函数一样?(无投票)

标签: javascriptasynchronouscallback

解决方案


您可以使用 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));


推荐阅读