异步/等待语法有时似乎不起作用

时间:2020-11-05 03:27:21

标签: javascript vue.js

我使用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并返回“结果”值后,函数B就会完成工作。

但是,有时函数B中的api在“ this.result”获得其值之前被称为“ another2 api”,即使在函数A从$ api接收到值后结果为“ true”

this is normal action which i expect

这是我期望的正常动作

enter image description here

这是一个错误,有时在刷新页面时会发现。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

A返回一个承诺。如果您的mounted()函数不是可以使用await的异步函数,则必须使用then

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

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

答案 1 :(得分:0)

您需要让已挂载的方法等待第一个方法再调用第二个方法。切记用async假装mount()。

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

答案 2 :(得分:0)

您需要将mounted设置为async

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

答案 3 :(得分:0)

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
  }
}