目前,我在存储操作中使用promises
,但希望将其转换为async/await
。这是一个包含promises的store操作的示例:
fetchActiveWorkspace (context, workspaceID) {
if (workspaceID) {
return this.$axios.get(`@api-v01/workspaces/workspace/${workspaceID}`)
.then(response => {
context.commit('setActiveWorkspace', response.data)
})
.catch(err => {
throw err
})
} else {
return Promise.resolve(true)
}
},
此fetchActiveWorkspace
操作在组件中解析,因为它返回promise
。如何将此代码片段转换为async/await
结构并在组件中使用?
发布于 2019-06-21 16:42:27
这就是我尝试翻译它的方式;考虑到由于我无法访问完整上下文中的原始代码,我不能直接尝试以确保其工作;但这仍然是您可以使用async/await
与promises的方式。
// 1. Mark the function as `async` (otherwise you cannot use `await` inside of it)
async fetchActiveWorkspace(context, workspaceID) {
if (workspaceID) {
// 2. Call the promise-returning function with `await` to wait for result before moving on.
// Capture the response in a varible (it used to go as argument for `then`)
let response = await this.$axios.get(`@api-v01/workspaces/workspace/${workspaceID}`);
context.commit('setActiveWorkspace', response.data);
}
// 3. I don't think this is necessary, as actions are not meant to return values and instead should be for asynchronous mutations.
else {
return true;
}
}
您可以用try/catch
包围函数体,以防您想要捕获和处理异常。我没有添加它是为了让事情变得简单,因为基于promise的代码只会捕获并重新抛出异常,而不会做其他任何事情。
https://stackoverflow.com/questions/56667685
复制相似问题