Axios发起HTTP请求时的先后执行顺序

书写如下代码时,日志输出的顺序不可控,可能是"you How are",也可能是"you are How"

html 复制代码
<script>
import axios from 'axios'
export default {
  created() {
    this.fn1()
    this.fn2()
    console.log('you')
  },

  methods: {
    fn1() {
      axios.get('https://random.dog/woof.json')
      .then(ret => {
        console.log('How')
      }).catch(e => {
        console.log(e)
      })

    },

    fn2() {
      axios.get('https://random.dog/woof.json')
      .then(ret => {
        console.log('are')
      }).catch(e => {
        console.log(e)
      })
    }

  }
}
</script>

如果希望日志输出顺序是"How are you",方案1代码如下:

html 复制代码
<script>
import axios from 'axios'
export default {
  name: 'App',
  async created() {
    await this.fn1()
    await this.fn2()
    console.log('you')
  },

  methods: {
    fn1() {
      return axios.get('https://random.dog/woof.json')
      .then(ret => {
        console.log('How')
      }).catch(e => {
        console.log(e)
      })

    },

    fn2() {
      return axios.get('https://random.dog/woof.json')
      .then(ret => {
        console.log('are')
      }).catch(e => {
        console.log(e)
      })
    }

  }
}
</script>

如果希望日志输出顺序是"How are you",方案2代码如下:

html 复制代码
<script>
import axios from 'axios'
export default {
  async created() {
    await this.fn1()
    await this.fn2()
    console.log('you')
  },

  methods: {
    async fn1() {
      const ret = await axios.get('https://random.dog/woof.json')
      console.log('How')
      console.log(ret.data)
    },

    async fn2() {
     const ret = await axios.get('https://random.dog/woof.json')
     console.log('are')
     console.log(ret.data)
    }

  }
}
</script>
相关推荐
草字19 分钟前
uniapp 打开横竖屏。usb调试时可以横竖屏切换,但是打包发布后却不行?
java·前端·uni-app
SEO-狼术22 分钟前
Stimulsoft Reports.JS 2025
开发语言·javascript·ecmascript
EF@蛐蛐堂24 分钟前
Federation vs Garfish vs Micro-app 微前端选型(二)
前端·vue.js·前端框架
洋不写bug29 分钟前
前端html基础标签
前端·html
GISer_Jing38 分钟前
前端学习总结——AI&主流前沿方向篇
前端·人工智能·学习
渣哥1 小时前
用错注入方式?你的代码可能早就埋下隐患
javascript·后端·面试
尘世中一位迷途小书童1 小时前
Monorepo 工具大比拼:为什么我最终选择了 pnpm + Turborepo?
前端·架构
一枚前端小能手1 小时前
🔍 重写vue之ref和reactive
前端·javascript·vue.js
星链引擎1 小时前
4sapi.com开发者进阶版(技术导向,侧重 “原理 + 最佳实践”)
前端
尘世中一位迷途小书童1 小时前
2025年了,你还在用传统的多仓库管理吗?Monorepo 架构深度解析
前端·架构