当其中一些失败时如何成功处理多个axios请求
How to handle several axios request successfully when some of them are failed
假设我有一个快速服务器需要连接(发送数据)几个快速服务器。像这样:
app.post('/events', async (req, res) => {
const event = req.body;
events.push(event)
try {
console.log(`event received ${event.type}`)
await axios.post('http://localhost:4000/events', event);
console.log('event sent to 4000')
await axios.post('http://localhost:4001/events', event);
console.log('event sent to 4001')
await axios.post('http://localhost:4002/events', event); //<-- server stopped hence go catch block
console.log('event sent to 4002')
await axios.post('http://localhost:4003/events', event); //<-- never come here
console.log('event sent to 4003')
} catch (e) {
console.log(e);
}
res.send({ status: 'OK' });
});
由于某种原因,其中一个快速服务器已停止。让端口 4002
上 运行 的服务器停止,但我无法 post 数据到 4003
上的服务器 运行 端口。有什么方法可以处理由 catch 块捕获的 ECONNREFUSED
错误以及将数据发送到 4003
上的服务器 运行 端口?
正如@jfriend00 建议您可以使用 Promise.allSettled()
,
const promise1 = axios.post('http://localhost:4000/events', event)
const promise2 = axios.post('http://localhost:4001/events', event)
const promise3 = axios.post('http://localhost:4002/events', event)
const promise4 = axios.post('http://localhost:4003/events', event)
const promises = [promise1, promise2, promise3, promise4];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
而不是 try/catch
。
假设我有一个快速服务器需要连接(发送数据)几个快速服务器。像这样:
app.post('/events', async (req, res) => {
const event = req.body;
events.push(event)
try {
console.log(`event received ${event.type}`)
await axios.post('http://localhost:4000/events', event);
console.log('event sent to 4000')
await axios.post('http://localhost:4001/events', event);
console.log('event sent to 4001')
await axios.post('http://localhost:4002/events', event); //<-- server stopped hence go catch block
console.log('event sent to 4002')
await axios.post('http://localhost:4003/events', event); //<-- never come here
console.log('event sent to 4003')
} catch (e) {
console.log(e);
}
res.send({ status: 'OK' });
});
由于某种原因,其中一个快速服务器已停止。让端口 4002
上 运行 的服务器停止,但我无法 post 数据到 4003
上的服务器 运行 端口。有什么方法可以处理由 catch 块捕获的 ECONNREFUSED
错误以及将数据发送到 4003
上的服务器 运行 端口?
正如@jfriend00 建议您可以使用 Promise.allSettled()
,
const promise1 = axios.post('http://localhost:4000/events', event)
const promise2 = axios.post('http://localhost:4001/events', event)
const promise3 = axios.post('http://localhost:4002/events', event)
const promise4 = axios.post('http://localhost:4003/events', event)
const promises = [promise1, promise2, promise3, promise4];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
而不是 try/catch
。