猿问

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

我的问题是,将 .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()


白板的微信
浏览 144回答 2
2回答

眼眸繁星

这取决于您对“问题”的含义,但是这段代码: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是可读性的正确选择。如果您将它用于可恢复的错误处理,它会很好地工作。

BIG阳

我想你要找的是这个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)  });}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答