Javascript 循环中的Axios:如果请求失败,如何跳过迭代?
我有一些端点数组:Javascript 循环中的Axios:如果请求失败,如何跳过迭代?,javascript,http,axios,Javascript,Http,Axios,我有一些端点数组: const nodes = [127.111.111.222, 127.111.111.333, 127.111.111.444] 我在循环中请求每个对象,并在另一个数组中收集响应对象: let response let nodes_data = [] // inside some async function try{ for(let node of nodes) { response = await axios.post(`http://${n
const nodes = [127.111.111.222, 127.111.111.333, 127.111.111.444]
我在循环中请求每个对象,并在另一个数组中收集响应对象:
let response
let nodes_data = []
// inside some async function
try{
for(let node of nodes) {
response = await axios.post(`http://${node}/`, {})
nodes_data.push({ host: node, status: 'online', response: response.data})
}
} catch(error) {
console.log('Failed to request', error)
}
现在,如果某个端点没有响应(注意:没有发送500+或任何其他状态代码,但根本没有响应),axios将等待5-7秒,并将运行时转换为“catch”块(连接运行时错误)。脚本停止工作
如何更改所有内容,以便在单个端点响应时间不足时,仍将对象推入“脱机”状态的节点\ u数据中,循环继续工作
爱我认为使用axios作为一种承诺,那么block会有所帮助。我在写你的代码
for(let node of nodes) {
axios.post(`http://${node}/`, {}).then(response =>
{
nodes_data.push({ host: node, status: 'online', response: response.data})
}).catch(error =>{
console.log(error);
}
}
您可能需要,它接受一个承诺数组并返回所有已确定的值,无论它们是已解决还是已拒绝
let promises = nodes.map(node => {
return axios.post(`http://${node}`, {});
});
let responses = Promise.allSetted(promises);
// you will get an array of values with the following signature:
// [
// {status: "fulfilled", value: {"response": "from axios", "awesome": true},
// {status: "rejected", reason: Axios went poof!}
// ]
提示:将try/catch放在循环中