我有一些端点数组:
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”块(连接运行时错误)。脚本停止工作。
如何更改所有内容,以便在单个端点响应时间耗尽的情况下,我仍然将对象推送到处于“脱机”状态的nodes_data中,并且循环继续工作?
爱<3
发布于 2021-05-01 14:50:20
我认为使用axios作为一个承诺,然后阻止将会有所帮助。我在重写你的代码。
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);
}
}
发布于 2021-05-01 16:15:21
您可能需要Promise.allSettled,它接受一个promises数组并返回所有已解决的值,而不管它们是已解决还是已拒绝。
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!}
// ]
https://stackoverflow.com/questions/67343559
复制相似问题