async和await中的try...catch

848 阅读2分钟

1.Promise对象 用来执行 业务函数

  • 如果 业务成功,则 应该调用 resolve 函数,实参 会被 传给 then 回调函数中
  • 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 回调函数中
  • 如果 出现异常,则 可以手动 会 自动 抛出异常,异常对象 会被 传给 catch 回调函数中
function hmtest() {
    new Promise(function (resolve, reject) {
        // 1.执行成功回调函数------------
        // resolve('大王,你快来抓我呀~!')

        // 2.执行失败(异常)回调函数------
        // reject('死鬼')
        // throw new Error('死鬼!'); // 手动抛出异常
        JSON.parse('asdfasdfasdf') // 自动抛出异常
    }).then((res1) => {
        console.log('res1->', res1)
    }).catch((e) => {
        console.log('---------------------------')
        console.log('出错啦:')
        console.dir(e)
        console.log('---------------------------')
    })
}

2.Promise对象 结合 async/await 关键字

  • 如果 业务成功,则 应该调用 resolve 函数,实参 会被返回给 前面的 res
  • 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 回调函数中
  • 如果 出现异常,则 可以手动或自动抛出异常,异常对象会被传给catch 回调函数中
async function hmtest1() {
    // a.调用
    const res = await new Promise(function (resolve, reject) {
        // 1.执行成功回调函数------------
        // resolve('大王,你快来抓我呀~!')

        // 2.执行失败(异常)回调函数------
        // reject('失败了~~!')
        throw new Error('死鬼!');
    }).catch((e) => {
        console.log('---------------------------')
        console.log('出错啦:')
        console.dir(e)
        console.log('---------------------------')
    })

    // b.打印结果
    console.log('res->', res)

}
}

hmtest2()

3.Promise对象 结合 async/await + try...catch... 代码块

  • 如果 业务成功,则 应该调用 resolve 函数,实参 会被返回给 前面的 res
  • 如果 业务失败,则 应该调用 reject 函数,实参 会被 传给 catch 代码块的形参
  • 如果 出现异常,则 可以手动或自动抛出异常,异常会被传给 catch 代码块的形参
async function hmtest2() {
    try {
        const res = await new Promise(function (resolve, reject) {
            // 1.执行成功回调函数------------
            // resolve('大王,你快来抓我呀~!')

            // 2.执行失败(异常)回调函数------
            // reject('讨厌!')
            throw new Error('死鬼!');
        })
        // 打印结果
        console.log(res)
    } catch (e) {
        console.log('---------------------------')
        console.log('出错啦:')
        console.dir(e)
        console.log('---------------------------')
    }
}