关于async和await的异常捕获

一般我们会想到用 try/catch和then().catch()

function getData(data) {
    return new Promise((resolve, reject) => {
        if (data === 1) {
            resolve('getdata success')
        } else {
            reject('getdata error')
        }
    })
}

// 这样写是捕获不到异常
async fn() {
    const res = await getData();
    console.log(res)
}

//方法1: try / catch
async fn() {
    try {
        const res = await getData();
        console.log(res)
    } catch {
        console.log(err)
    }
}

// 方法2: then().catch()
async fn() {
    const res = await getData()
                .then(res => {
                    console.log(res)
                })
                .catch(err => {
                    console.log(err)
                })
}

// 一般选择用如果有多个请求,则需要重复写try/catch,冗余代码,因此可以封装
test(fn) {
    return new Promise(async resovle => {
        try {
            let res = await fn;
            resolve([null, res]); // 对应【err, res】
        } catch(err) {
            resolve([err, null])
        }
    })
}

async fn() {
    const [err, res] = await test(getData())
    console.log(err, res)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值