如何在 vue.js 中有一个条件异步操作



我正在使用 vue.js 2.* .我想对一个项目执行操作,但首先,我检查该项目是否存在,如果不存在,我就通过 API 获取它。我当前的代码如下所示:

if (myItem == null) {
this.goFetchItem().then(response => {
myItem.performAction()
})
} else {
myItem.performAction()
}

我想知道是否有可能在以下想法中有一些东西:

if (myItem == null) {
this.goFetchItem()
}
//And then, when item is fetched :
myItem.performAction()

目前,在第二个示例中,似乎goFetchItem()是异步执行的,因此myItem尝试执行该操作时仍然null

使用async / await怎么样?

async function foo() {
if (myItem == null) {
await this.goFetchItem()
}
myItem.performAction()
}

看看这个。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Javascript Promise vs Async Await.差异?

最新更新