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>
相关推荐
wayman_he_何大民几秒前
初始机器学习算法 - 聚类分析
前端·人工智能
wycode2 分钟前
Vue2实践(3)之用component做一个动态表单(二)
前端·javascript·vue.js
用户10922571561017 分钟前
你以为的 Tailwind 并不高效,看看这些使用误区
前端
意会32 分钟前
微信闪照小程序实现
前端·css·微信小程序
onejason32 分钟前
《利用 Python 爬虫获取 Amazon 商品详情实战指南》
前端·后端·python
用户67375280188436 分钟前
鸿蒙开发:应用内如何做更新
前端
zxhnext1 小时前
LLM大语言模型入门
前端·后端
知心宝贝1 小时前
写了那么久的前端,你真的了解浏览器背后的“小动作“吗?
前端·程序员·浏览器
wycode1 小时前
Vue2实践(2)之用component做一个动态表单(一)
前端·javascript·vue.js
维李设论1 小时前
前端智能化 | AG-UI实践及原理浅析
前端·aigc·agent