我有一个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);
}
)