axios 异步操作执行顺序

submitPwd () {
      if (this.oldPwd !== '' && this.newPwd !== '' && this.password !== '') {
        console.log(111)
        axios.post(httpUrl.checkOldPwd, this.oldPwd)
        .then(res => {
          console.log(222)
          this.status = true
        })
        .catch(err => console.log(err))
        console.log(333)
        console.log(this.status)
        if (this.status) {
          console.log('旧密码验证通过')
        } else {
          console.log('旧密码输入错误')
        }
      } else {
        console.log('密码不能为空')
      }
    }

data中 status: false

以上代码为一个提交密码的方法案例,理想状态的输出顺序应该是:
111
222
333
true
旧密码验证通过

但是实际输出顺序是:
111
333
false
旧密码输入错误
222

这是为什么?

阅读 7.3k
2 个回答

因为你的console.log(333)是在catch外面的。。
如果看不懂的话,学习一下Promise

axios是异步请求,在它外面且在下面的代码不会等待它完成,会直接开始运行,而异步请求体里面的内容会在其请求成功或者失败才执行相应的代码。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题