简体   繁体   English

Vue 方法不接受异步/等待

[英]Vue method not accepting async/await

I am working on a Vue.js project where I am trying to run a series of promises depening on each other.我正在研究一个 Vue.js 项目,我正在尝试运行一系列相互依赖的承诺。 To make this example simple I have cut out all but one and replaced the rest with a console.log which should output the value I am trying to access to then use later on.为了使这个例子简单,我已经删除了除一个之外的所有内容,并用 console.log 替换了 rest,它应该 output 是我试图访问然后稍后使用的值。 If I can get this example to work then the rest is just repeating it.如果我能让这个例子工作,那么 rest 只是重复它。

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');
    },

Real results:实际结果:

I see the console.log fire off with undefined, then the alert then the awaited promise/function shows in the vue dev tools.我看到 console.log 在未定义的情况下触发,然后警报然后等待的承诺/功能显示在 vue 开发工具中。

How can I get this so that I can get the result of the createBuilding method to use with my other methods?我怎样才能得到这个,以便我可以得到 createBuilding 方法的结果以与我的其他方法一起使用?

This is promise constructor antipattern.这是 promise 构造函数反模式。 There's no need to use new Promise in case a promise already exists and can be chained.如果 promise 已经存在并且可以链接,则无需使用new Promise The antipattern leaves the space for mistake, which is the case here.反模式为错误留下了空间,这里就是这种情况。

newBuilding is expected to be asynchronous, but the promise is resolved instantly, this results in race condition. newBuilding预计是异步的,但 promise 会立即解决,这会导致竞争状况。

It should be:它应该是:

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

With async..await , it's simplified to:使用async..await ,它被简化为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM