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 小时前
JitWord Office预览引擎:如何用Vue3+Node.js打造丝滑的PDF/Excel/PPT嵌入方案
前端·vue.js·github
晴殇i1 小时前
揭秘JavaScript中那些“不冒泡”的DOM事件
前端·javascript·面试
孟陬1 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
BER_c1 小时前
前端权限校验最佳实践:一个健壮的柯里化工具函数
前端·javascript
兆子龙2 小时前
别再用 useState / data 管 Tabs 的 activeKey 了:和 URL 绑定才香
前端·架构
sudo_jin2 小时前
前端包管理器演进史:为什么 npm 之后,Yarn 和 pnpm 成了新宠?
前端·npm
敲敲敲敲暴你脑袋2 小时前
写个添加注释的vscode插件
javascript·typescript·visual studio code
叁两2 小时前
用opencode打造全自动公众号写作流水线,AI 代笔太香了!
前端·人工智能·agent
golang学习记3 小时前
GitLens 十大神技:彻底改变你在 VS Code 中的 Git 工作流
前端·后端·visual studio code
SuperEugene3 小时前
后台权限与菜单渲染:基于路由和后端返回的几种实现方式
前端·javascript·vue.js