我正在使用 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 - 如何在 vue.js 中进行条件异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043247/