async和await中的try...catch

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('---------------------------')
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容