javascript - 返回具有异步功能的事件主机

标签 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);

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

最佳答案

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

相关文章:

c++ - 回调函数中的接口(interface)类导致崩溃

asynchronous - 将数据从 BigQuery 导出到 GCS - 可以部分传输吗?

c# - 我连续调用多个异步方法是否正确?

javascript - 如何在 RequireJS 中混合 Underscore 插件?

c++ - 指定内联回调函数作为参数

javascript - Onclick 中的两个 Javascript 函数

javascript - 如何更改 base64 格式的 svg img 的颜色?

javascript - 使用 jQuery 删除子项的事件处理程序但不删除自身的事件处理程序

javascript - 如何使用 Javascript 调用 CSS 动画

linux - 使用hrtimer回调函数,是否可以给函数参数?