我正在做一个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开发工具中显示了警报和等待的promise/function。
我如何才能获得createBuilding方法的结果,以便与其他方法一起使用呢?
发布于 2021-05-12 01:32:32
这是promise构造函数反模式。如果promise已经存在并且可以链接,则不需要使用new Promise。反模式为错误留下了空间,这里就是这种情况。
newBuilding应该是异步的,但promise是立即解析的,这会导致竞争条件。
它应该是:
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
}
},https://stackoverflow.com/questions/67491599
复制相似问题