await为什么要和trycatch一起使用?

229 阅读1分钟

1、不用try catch

const p1 = () => {
    return new Promise((resolve,reject) => {
        reject('报错')
    })
}

const p2 = async () => {
    const resp1 = await p1()
    console.log('resp1:', resp1)
}
p2()
console.log('进行到这')

运行输出:
image.png

2、使用.catch捕获reject信息

const p1 = () => {
    return new Promise((resolve,reject) => {
        reject('报错')
    })
}

const p2 = async () => {
    const resp1 = await p1()
    console.log('resp1:', resp1)
}
p2().then(resp2 => {
    console.log('resp2:', resp2)
}).catch(errp2 => {
    console.log('errp2:', errp2)
})
console.log('进行到这')

运行输出:

image.png

3、使用try-catch捕获reject信息

const p1 = () => {
    return new Promise((resolve,reject) => {
        reject('报错')
    })
}

const p2 = async () => {
    try {
        const resp1 = await p1()
        console.log('resp1:', resp1)
    } catch (errp1) {
        console.log('errp1:', errp1)
    }
}
p2()
console.log('进行到这')

运行输出,可以看到reject的信息被catch捕获

image.png

综上可以看到在await外面包裹一层try catch可以直接捕获await后面promise的reject的错误

那么使用try-catch捕获reject信息,后面p2的then会执行吗?

const p1 = () => {
    return new Promise((resolve,reject) => {
        reject('报错')
    })
}

const p2 = async () => {
    try {
        const resp1 = await p1()
        console.log('resp1:', resp1)
    } catch (errp1) {
        console.log('errp1:', errp1)
    }
}
p2().then(resp2 => {
    console.log('resp2:', resp2)
}).catch(errp2 => {
    console.log('errp2:', errp2)
})
console.log('进行到这')

运行输出:

image.png

由此可见reject的信息只会被捕获一次,之后都只会执行then的回调函数