async 和 await 之失败了怎么办

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

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

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

点击确定会执行 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: '已取消删除'
        })
      }
    }
  }
}
发布了138 篇原创文章 · 获赞 51 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/mynewdays/article/details/103315905
今日推荐