为了账号安全,请及时绑定邮箱和手机立即绑定

将 .catch 与异步等待一起使用会导致问题吗?

将 .catch 与异步等待一起使用会导致问题吗?

白板的微信 2022-05-22 10:28:07
我的问题是,将 .catch 与 async await 一起使用会导致问题吗?例如:function f1() {  return new Promise((res, rej) => {    rej(1)  })}async function f2() {  await f1().catch(ex => { }) // this is what I mean}f2()
查看完整描述

2 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

这取决于您对“问题”的含义,但是这段代码:


async function f2() {

  await f1().catch(ex => { /* ... code in catch ... */ }) // this is what I mean

}

相当于:


async function f2() {

  try {

    await f1()

  } catch (ext) {

    /* ... code in catch ... */

  } // this is what I mean

}

.catch正如您所说,使用它而不是按try-catch原样使用可能很有用- 并非在每种情况下 - 都可以使您的代码更具可读性。但是您需要始终考虑是否.catch是可读性的正确选择。如果您将它用于可恢复的错误处理,它会很好地工作。


查看完整回答
反对 回复 2022-05-22
?
BIG阳

TA贡献1859条经验 获得超6个赞

我想你要找的是这个


function f1(){

  return new Promise((res,rej)=>{

    rej(1)

  })

}


async function f2(){

  try {

    const response = await f1();

    // use the response from f1()

  } catch(err) {

    throw new Error(err);

  }

}


f2()

沿着这些思路的东西async/await是承诺的包装,允许您编写看起来同步的代码。否则你会看


function f2(){

  let response;

  f1().then(res => {

    response = res

  })

  .catch(err => {

    throw Error(err)

  });

}


查看完整回答
反对 回复 2022-05-22
  • 2 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号