[Interview question] Do async/await functions need to add try catch?

1. Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

foreword

When writing asynchronous functions, both promise and async solutions are very common. Even in the same project, different developers use different habits. However, the comparison between the two is not the focus of this article. It can only be summarized in one sentence: "async is the ultimate solution for asynchronous programming".

When using the async function, many articles suggest using to try catchcatch exceptions, but actually I read the codes of many projects, and the codes are not strictly followed, many of them are useless, even the catch function is not written, why is that?

Let's first look at the code example in the case of using try catch:

Example 1: Using try catch

function getUserInfo () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
                reject('请求异常')
        }, 1000)
    })
}

async function logined () {
    try {
        let userInfo = await getUserInfo()
        // 执行中断
        let pageInfo = await getPageInfo(userInfo?.userId)
    } catch(e) {
        console.warn(e)
    }
}

logined()

After execution, it will be captured in the catch 请求异常, and then the getUserInfo function will interrupt the execution, which is logical. For interfaces with dependencies, interrupting the execution can avoid program crashes. The only problem here is that the try catch seems to occupy too many lines. If each interface is written, it looks slightly redundant.

Example 2: Direct catch

Given that under normal circumstances, awaitthe command is followed by a Promise object, so the above code can naturally think of an optimization solution:

function getUserInfo () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
                reject('请求异常')
        }, 1000)
    })
}

async function logined () {
    let userInfo = await getUserInfo().catch(e => console.warn(e))
    // 执行没有中断,userInfo 为 undefined
    if (!userInfo) return // 需要做非空校验
    let pageInfo = await getPageInfo(userInfo?.userId)
}

logined()

After execution, the catch can catch the exception normally, but the program is not interrupted, and the return value userInfois undefined, so if it is written like this, it is necessary to check the return value for non-nullness. if (!userInfo) returnI think this is a bit counter-logic, and the execution should be interrupted when there is an exception;

Example 3: reject in catch

You can continue to optimize, adding a line in the catch return Promise.reject(e)can make await interrupt execution;

Full code:

function getUserInfo () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            reject('请求异常')
        }, 1000)
    })
}

async function logined () {
    let userInfo = await getUserInfo().catch(e => {
        console.warn(e)
        return Promise.reject(e) // 会导致控制台出现 uncaught (in promise) 报错信息
    })
    // 执行中断
    let pageInfo = await getPageInfo(userInfo?.userId)
}

logined()

Generally, we use axios or fetch to send requests in the project, which will be encapsulated, and the catch operation can also be performed in it, and the error information will be processed first. As for whether you need to reject, it depends on whether you want to interrupt when the await command is abnormal uncaught (in promise).

Screenshot 2023-03-22 16.55.14.png

suggestion

There is no need to interrupt when the await is abnormal, you can write it like this, you need to do a non-null check, and the console will not report an error message

let userInfo = await getUserInfo().catch(e => console.warn(e))
if (!userInfo) return

Need to interrupt when await is abnormal, and care about console error, you can write like this

 
 
try {
    let userInfo = await getUserInfo()
    // 执行中断
    let pageInfo = await getPageInfo(userInfo?.userId)
} catch(e) {
    console.warn(e)
}

If you need to interrupt when the await is abnormal, but you don't care about the console error, you can write like this

let userInfo = await getUserInfo().catch(e => {
    console.warn(e)
    return Promise.reject(e) // 会导致控制台出现 uncaught (in promise) 报错信息
})
// 执行中断
let pageInfo = await getPageInfo(userInfo?.userId)

Summarize

Several ways of writing, at first glance, you may think that the third way of writing catch is the best, but after thinking about it, from the perspective of user experience, I think try catch is the best, logical and intuitive, in line with synchronous programming thinking, and the console will not expose error messages uncaught (in promise);

The catch (reject inside) of the chain call is the callback writing method of the traditional promise. Since the synchronous programming method of async await has been used, it feels unnecessary to use the catch chain writing method.

1. Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131902012