我有一个API fetch WAIT代码,用于获取数组中的 node 列表.问题是,有些 node 无论出于何种原因都没有响应(离线、端口错误、被编程为不响应……)我的代码一直在等待那个 node 的回复.

如果没有响应,有没有办法停止等待取数(例如3秒后)?

我try 使用try-and-catch,但是没有响应的 node 不会返回任何内容,代码只是简单地放在那里,没有错误或响应.

非常感谢.

// list of nodes        
let nodes = [{
                "address": {
                    "hostname": "192.168.1.1",
                    "port": 31350
                }
            }, {
                "address": {
                    "hostname": "192.168.1.2",
                    "port": 31350
                }
            }
        ]
    
    
// api fetch function    
    async function fetchNodes(hostname, port) {
    
      const response = await fetch(`https://${hostname}:${port}/getstatus`, {
      method: 'post',
      body: JSON.stringify(body),
      headers: {'Content-Type': 'application/json'}
      });

      const data = response.json();   
      console.log(data);
    
    }
    
// loop to call api fetch function with all array entries       
    nodes.forEach(function(entry) {
     fetchNodes(entry.address.hostname, entry.address.port);
        }
    )

推荐答案

试试这个

 async function fetchWithTimeout(resource, options = {}) {
  const { timeout = 8000 } = options;
  
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
  const response = await fetch(resource, {
    ...options,
    signal: controller.signal  
  });
  clearTimeout(id);
  return response;
}

并在fetchNodes函数中使用此函数

  async function fetchNodes() {
  try {
    const response = await fetchWithTimeout(
      `https://${hostname}:${port}/getstatus`,
      {
        timeout: 6000,
        method: "post",
        body: JSON.stringify(body),
        headers: { "Content-Type": "application/json" },
      }
    );
    const data = await response.json();
    return data;
  } catch (error) {
    // Timeouts if the request takes
    // longer than 6 seconds
    console.log(error.name === "AbortError");
  }
}

Javascript相关问答推荐

有条件的悲剧

zoom svg以适应圆

在页面上滚动 timeshift 动垂直滚动条

调用removeEvents不起作用

无法在nextjs应用程序中通过id从mongoDB删除'

加载背景图像时同步旋转不显示的问题

编剧如何获得一个div内的所有链接,然后判断每个链接是否都会得到200?

material UI按钮组样式props 不反射

当输入字段无效时,我的应用程序不会返回错误

元素字符串长度html

将异步回调转换为异步生成器模式

为什么我的按钮没有从&q;1更改为&q;X&q;?

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

OnClick更改Json数组JSX中的图像源

Next.js无法从外部本地主机获取图像

每隔3个项目交替显示,然后每1个项目交替显示

如何从嵌套的json中获取最大值

对象作为react 子对象无效(已找到:具有键的对象{type,props}).如果要呈现一个子级集合,请改用数组

制表机表宽度在第一次加载时缩小,拖动后正在调整

根据网络速度加载CS