假设我有一个快递服务器,它需要连接(发送数据)多个快递服务器。像这样:
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
上运行的服务器已停止,但是我无法将数据发布到在4003
上运行端口的服务器上。有什么方法可以处理由catch块捕获的ECONNREFUSED
错误,以及将数据发送到4003
上的服务器运行端口吗?
答案 0 :(得分:0)
按照@ 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
。