async 和 await 之失败了怎么办 您所在的位置:网站首页 api获取失败101怎么办 async 和 await 之失败了怎么办

async 和 await 之失败了怎么办

2023-04-01 23:00| 来源: 网络整理| 查看: 265

下面看一下 element 中的弹出框案例

点击打开 Message Box export default { methods: { open () { this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { this.$message({ type: 'success', message: '删除成功!' }) }).catch(() => { this.$message({ type: 'info', message: '已取消删除' }) }) } } }

效果很简单:点击按钮弹出确认框,可以选择 确定 或者 取消

点击确定会执行 then 方法中的代码,点击 取消会执行 catch 中的代码

下面使用 async 与 await 进行改写

export default { methods: { async open () { await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }) this.$message({ type: 'success', message: '删除成功!' }) } } }

减少了一个 then 方法,但是 catch 方法的代码应该放到哪里呢?因为 then 方法中的代码都是 revole 返回后执行的代码,但是 catch 中都是 rejected 返回执行的代码

这里使用 try catch 解构就可以了

export default { methods: { async open () { try { await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }) this.$message({ type: 'success', message: '删除成功!' }) } catch (e) { this.$message({ type: 'info', message: '已取消删除' }) } } } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有