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>
相关推荐
烂蜻蜓1 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
Rowrey2 小时前
react+typescript,初始化与项目配置
javascript·react.js·typescript
谢尔登2 小时前
Vue 和 React 的异同点
前端·vue.js·react.js
祈澈菇凉6 小时前
Webpack的基本功能有哪些
前端·javascript·vue.js
小纯洁w6 小时前
Webpack 的 require.context 和 Vite 的 import.meta.glob 的详细介绍和使用
前端·webpack·node.js
想睡好7 小时前
css文本属性
前端·css
qianmoQ7 小时前
第三章:组件开发实战 - 第五节 - Tailwind CSS 响应式导航栏实现
前端·css
记得早睡~7 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
zhoupenghui1687 小时前
golang时间相关函数总结
服务器·前端·golang·time
White graces7 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea