有了 Promise 链式语法,从此告别 try-catch

223 阅读1分钟

小伙伴们平常怎么捕获异步事务的异常的,大家都知道,万事不决 try-catch,直接包就完事了,大家不觉得每次都得try-catch太麻烦了吗,我只想捕获一个异步请求的错误还得专门包一下。

用 async await 的知识我用链式语法优化了一下。

这里结合 ElementUI 中的 confirm 确认框组件当个例子。

// $confirm promise 语法
// $confirm 的结果是 promise 对象, 所以才可以 .then  .catch(并且可以多次.then 多次.catch来链式调用)
// 当用户点击确定时, confirm 组件会进入成功的回调,点击失败,进入失败的回调
// resolved 成功的  ==>  成功的回调, 用户点确定会执行这个
// rejected 失败的  ==>  失败的回调, 用户点取消会执行这个

这里有一个注意点,就是 await 只能处理 then 的情况,即只能捕获成功的 Promise

1. 以前的写法

需要使用 try-catch 去捕获 await 之后的异常情况

      this.$confirm('确定删除该角色吗?', '提示', {
        type: 'warning'
      })
        .then(async() => {
          try {
            // 2. 用户确定后, 发请求删除
            const res = await delRoleById(id)
            // 3. 删除完毕后根据结果提醒用户
            this.$message.success(res.message)
            // 4. 重新发请求获取数据
            this.loadRoles()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(e => {})

2. 优化后的写法

await代替了.then,.catch 代替了 try-catch

难点:如果进入了catch,如果进这里相当于后面默认有一个then(),catch的返回值作为了这个then的实参,然后这个隐藏then的实参又被await捕获了,最终传到res中

 const result = await this.$confirm('确定删除该角色吗?', '提示', {
        type: 'warning'
      })
      // .then(res => {res}) // res 是 confirm,这里被await代替了
        .catch(e => e) // 返回值是 e, e 是 cancel
      // 在 promise 的串行任务中, 每一次回调函数(包括 .then 和 .catch)中返回的结果, 会作为下一个 .then 的参数。
      // console.log(result)
      // 1.用户点击取消就直接 return
      if (result !== 'confirm') return

	 // 表示用户点确定
      // 用户确定后, 发请求删除
      const res = await delRoleById(id).catch(e => e)
      if(!res.success) return this.$message.error(e.message)//没有就是undefined
      // 这里$message返回的是message实例对象,捕获错误需要和后端约定一个字段,比如success为true表示操作成功(或者是约定一个操作成功的code),不能直接在catch中$message
      //  删除完毕后根据结果提醒用户
      this.$message.success(res.message)