返回具有异步功能的活动主机

时间:2018-12-23 14:30:18

标签: javascript asynchronous callback

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

由于主机的状态是通过回调(异步)确定的,因此如何返回一个或多个主机的状态,就像上面的函数一样? (不进行轮询)

1 个答案:

答案 0 :(得分:1)

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