V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
solaro
V2EX  ?  前端开发

vue 中 axios 如何实现异步并发,并且并发不因为某个请求失败而导致整个并发失败?

  •  
  •   solaro · 2022-03-20 17:46:42 +08:00 · 1125 次点击
    这是一个创建于 785 天前的主题,其中的信息可能已经有所发展或是发生改变。

    腾讯云最新优惠活动来了:云产品限时1折,云服务器低至88元/年 ,点击这里立即抢购:9i0i.cn/qcloud,更有2860元代金券免费领取,付款直接抵现金用,点击这里立即领取:9i0i.cn/qcloudquan

    (福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

    代码如下:

    <script>
    import axios from 'axios'
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      },
      data() {
        return {
          r1: '',
          r2: '',
          r3: ''
        }
      },
      created() {
        this.getData()
      },
      methods: {
        getData() {
          axios.all([
            axios.get('http://baidu.com'),
            axios.get('https://163.com'),
            axios.get('https://google.com')
          ]).then(
            axios.spread(function(r1, r2, r3) {
              console.log(r1, r2, r3)
            })
          ).catch(error => console.log(error))
        }
      }
    }
    </script>
    

    问题:

    • 1.前面两个 get 成功,第三个 get 失败了,整个 axios 请求都失败了,直接 catch 到 error 了

    期待:

    • 1.就算第三个失败了,前面两个也能赋值给 r1 、r2 ,第三个失败就失败了。
    3 条回复  ?  2022-03-20 22:31:53 +08:00
    Axnir
        1
    Axnir  
       2022-03-20 18:03:27 +08:00   ?? 1
    用 Promise.allSettled 吧
    solaro
        2
    solaro  
    OP
       2022-03-20 19:34:55 +08:00
    @Axnir 我试试
    solaro
        3
    solaro  
    OP
       2022-03-20 22:31:53 +08:00
    @Axnir 搞定,谢谢大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1069 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:06 · PVG 03:06 · LAX 12:06 · JFK 15:06
    Developed with CodeLauncher
    ? Do have faith in what you're doing.


    http://www.vxiaotou.com