假设我有一个快速服务器,它需要连接(发送数据)多个快速服务器。如下所示:
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上运行端口的服务器?
发布于 2020-08-29 06:19:35
如@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。
https://stackoverflow.com/questions/63643945
复制相似问题