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

6次阅读

共计 1633 个字符,预计需要花费 5 分钟才能阅读完成。

论断

  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()

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

正文完
 0