关于javascript:promise和async的相互转换和错误捕捉

论断

  1. promise 用谬误回调和.catch()来处理错误
  2. async用.catch()和try{}catch(){}来捕获谬误

可能是从jQuery用过去的,集体更喜爱promise的写法

痛点er

到了新公司出奇的忙,忙着相熟文化、制度、框架、业务。业务中对异步的封装和应用混合了promise和async,要把这两种写法关系理清。

promise工厂

function pr(flag = true) { return new Promise((res, rej) => { setTimeout(() => { flag ? res("success") : rej("error") }, 2000) }) }

promise 的谬误捕获

谬误回调解决reject(),.catch()解决抛出的异样和reject(),

function catch1() {
  pr(false).then(() => {
    // error函数捕获不到这个谬误
    throw 'catch1 error'
  }, (e) => {
    // 只能解决promise的reject()谬误
    console.log('catch1 reject', e)
  })
}
function catch2() {
  pr().then(() => {
    // catch函数能够捕捉到这个谬误
    throw 'catch2 error'
  }).catch((e) => {
    // 解决reject() ,
    //解决胜利回调和谬误回调throw出的谬误
    console.log('catch2', e)
  }).finally(() => {
    console.log('catch2 , finally')
  })
}
catch1()
catch2()

async函数的谬误捕获

async function catch3() {
  try {
    const res = await pr(false).catch((e) => {
        // 能够省略让上面的catch捕获
      // reject会被捕获
      console.log(3, 'catch()', e)
      throw e
    })
    console.log('catch3', res)
    throw "error test"
    return res
  } catch (e) {
    console.log('catch3 try catch', e)
    throw e
  }
}
catch3()

promise和async的互相转换和谬误捕获

async是promise的语法糖

async function asy(){ return await 1 }
asy() instanceof  Promise // true
async function catch3() {
  // promise转await
  try {
    const res = await pr()
    console.log(3, 'catch3', res)
    throw "catch3 throw error"
    return res
  } catch (e) {
    console.log(3, 'try catch', e)
    // 捕获下面的throw
    // 如果下面没有异样回调,异样回调会在这捕获,再抛出也会被前面的异样回调捕捉到
    throw e
  }
}

async function catch4() {
  // try catch 和.catch()二选一
  // 捕获catch3谬误回调抛出的异样
  // 捕获catch3的throw
  try {
    await catch3().catch((e) => {
      console.log(4, 'catch()', e)
    })
  } catch (e) {
    console.log(4, 'try catch', e)
  }
};

function catch5() {
  // async 转promise
  // 谬误回调 和.catch()二选一
  catch3().then(() => {
  }, (e) => {
    console.log(5, 'reject()', e)
  }).catch((e) => {
    console.log(5, 'catch()', e)
  })
}
catch4()
catch5()

如果感觉对小伙伴有帮忙请点赞!
如果感觉对小伙伴有帮忙请点赞!
有谬误的中央欢送小伙伴斧正!!
有谬误的中央欢送小伙伴斧正!!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理