【问题标题】:async/await syntax sometimes seemed not workingasync/await 语法有时似乎不起作用
【发布时间】:2020-11-05 03:27:21
【问题描述】:

我正在使用 Vue 并想使用 async/await 为我的函数 A 和 B 提供序列

result is false by default    

mounted() {
  this.A();
  this.B();
}

async A() {
  this.result = await this.$api...
}

async B() {
  if(this.result) let data = await this.$another1 api...
  else let data = await this.$another2 api...
}

我假设在函数 A 调用 api 并返回一个 'result' 值之后,函数 B 完成了他的工作。

但是,有时函数 B 中的 api 在 'this.result' 之前调用 'another2 api' 会得到他的值,即使在函数 A 从 $api 接收值之后结果为 'true' 也是如此

这是我期望的正常操作

这是我刷新页面时有时会发现的错误。

我该如何解决这个问题?

【问题讨论】:

  • 一个异步函数返回一个可以等待的promise,或者使用.then()在第一个函数完成后执行第二个函数。

标签: javascript vue.js


【解决方案1】:

您需要将mounted 设为async

async mounted() {
  await this.A();
  await this.B();
}

【讨论】:

    【解决方案2】:

    A 返回一个承诺。如果您的mounted() 函数不是能够使用await 的异步函数,那么您将不得不使用then

    this.A().then(()=>{
       this.B();
    });
    

    (对不起,上面是打字稿。你可以弄清楚如何做javascript......这根本不是我的专长。)

    【讨论】:

    • 你的 TypeScript sn-p 在 JavaScript 中是一样的。
    • this 的东西是我在 javascript 中一直遇到的问题
    【解决方案3】:

    在调用第二个方法之前,你需要告诉挂载的方法等待第一个方法。记得用async 假装mounted()。

    async mounted() {
      await this.A();
      this.B();
    }
    

    【讨论】:

      【解决方案4】:
      mounted() {
        Promise.all([this.a(), this.b()])
               .then((res) => {
                     console.log(res)
               })
      }
      
      async A() {
        const result = await this.$api...
        return result
      }
      
      async B() {
        if(this.result) {
               const data = await this.$another1 api...
               return data
        } else {
                const data = await this.$another2 api...
                return data
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-20
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        • 2021-03-08
        • 2015-08-18
        • 1970-01-01
        • 2018-06-09
        • 1970-01-01
        相关资源
        最近更新 更多