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>
相关推荐
程序员黑豆3 小时前
Java包装类:基本类型与对象的桥梁
java·前端·ai编程
bugcome_com6 小时前
JWT 知识小课堂:从入门到精通,一文吃透 JSON Web Token
前端·json
To_OC6 小时前
写了三天 Next.js,我的 React 世界观被拆了又装回去
前端·全栈·next.js
独泪了无痕6 小时前
viewer.js 安装与配置指南:实现图片预览功能
前端·vue.js
起床学FPGA8 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
Fluxart.ai8 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
why技术9 小时前
AI 写的文章,可能都带着手敲一遍都去不掉的“隐形水印”。
前端·人工智能·后端
愚公搬代码9 小时前
【愚公系列】《Android应用案例开发大全》016-LBS类应用掌上杭州(辅助工具类的开发)
android·前端
CodeSheep9 小时前
又一个华为天才少年,离职了!
前端·后端·程序员
kyriewen9 小时前
面试官说"打开你的AI工具"——我才发现,他考的根本不是写代码
前端·人工智能·面试