首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在几个axios请求失败时成功地处理它们

如何在几个axios请求失败时成功地处理它们
EN

Stack Overflow用户
提问于 2020-08-29 05:56:59
回答 1查看 16关注 0票数 0

假设我有一个快速服务器,它需要连接(发送数据)多个快速服务器。如下所示:

代码语言:javascript
复制
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上运行端口的服务器?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-29 06:19:35

如@jfriend00所示,您可以使用Promise.allSettled()

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63643945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档