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>
相关推荐
努力学习的小刘2 分钟前
如何使用react-router实现动态路由
前端·javascript
PasserbyX2 分钟前
JS原型链
前端·javascript
curdcv_po3 分钟前
你知道Cookie的弊端吗?
前端
curdcv_po5 分钟前
前端CSS高频面试题详解
前端
Danta8 分钟前
从0开始学习three.js(1)😁
前端·javascript·three.js
我的心巴8 分钟前
vue-print-nb 打印相关问题
前端·vue.js·elementui
coderYYY28 分钟前
element树结构el-tree,默认选中当前setCurrentKey无效
前端·javascript·vue.js
GISer_Jing38 分钟前
Three.js中AR实现详解并详细介绍基于图像标记模式AR生成的详细步骤
开发语言·javascript·ar
GISer_Jing1 小时前
[总结篇]个人网站
前端·javascript
ss.li1 小时前
TripGenie:畅游济南旅行规划助手:个人工作纪实(二十二)
javascript·人工智能·python