Vue 方法不接受异步/等待

时间:2021-05-11 17:23:37

标签: javascript vue.js vuex

我正在一个 Vue.js 项目中工作,我试图在其中运行一系列相互依赖的承诺。为了使这个例子简单,我删掉了除一个之外的所有内容,并用一个 console.log 替换了其余部分,该日志应该输出我尝试访问的值,然后稍后使用。如果我能让这个例子起作用,那么剩下的就是重复它。

createBuilding: function() {
      return new Promise((resolve, reject) => {
        if(this.building === 'New building') {
          this.$store.dispatch('newBuilding', {
            address: this.address,
            number_units: this.number_units
          })
          .catch(err => {
            reject(err)
          })
          resolve(this.$store.getters.buildingID)
        } else {
          resolve(this.building)
        }
      }) 
    },
    onComplete: async function() {
      let buildingID = await this.createBuilding()
      console.log(buildingID)
      alert('Success');
    },

真实结果:

我看到 console.log 以 undefined 触发,然后是警报,然后是等待的承诺/函数显示在 vue 开发工具中。

我怎样才能得到这个,以便我可以得到 createBuilding 方法的结果以与我的其他方法一起使用?

1 个答案:

答案 0 :(得分:1)

这是承诺构造函数的反模式。如果承诺已经存在并且可以链接,则无需使用 new Promise。反模式为错误留下了空间,这里就是这种情况。

newBuilding 预计是异步的,但承诺会立即解决,这会导致竞争条件。

应该是:

createBuilding() {
    if(this.building === 'New building') {
      return this.$store.dispatch('newBuilding',...)
      .then(() => this.$store.getters.buildingID)
    } else {
      return Promise.resolve(this.building)
    }
},

使用 async..await,它被简化为:

async createBuilding() {
    if(this.building === 'New building') {
      await this.$store.dispatch('newBuilding',...);
      return this.$store.getters.buildingID
    } else {
      return this.building
    }
},