如何优雅处理 async/await 中的错误?

我们都知道 async/await 是 promise 的语法糖。

	// 模拟请求接口, 返回的是 Promise 对象. 
    const request = success => {
    	// 请求耗时 0 ~ 2 秒
        const wait = Math.random() * 2000
        console.log('请求时间', wait)
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                success ? resolve('ok') : reject('fail')
            }, wait)
        })
    }

promise 使用 then 方法和 catch 方法处理

	request(true).then(res => {
		console.log('res', res)
	}).catch(err => {
		console.log('err', err)
	})

使用 async/await 优化

	(async () => {
		const res = await request(true)
		console.log('res', res)
	})()

当 success 参数为 false 时

	(async () => {
		const res = await request(false)
		console.log('res', res)
	})()

报错如下:
在这里插入图片描述

像上面这样的写法,async/await 无法处理抛出的错误和 reject 的内容

第一种解决方案 :

	(async () => {
		const res = await request(false).catch(err => console.log('err', err))
		console.log('res', res)
	})()

第二种解决方案:

    (async () => {
        try {
            const res = await request(false)
            console.log('res', res)
        } catch(err) {
            console.log('err', err)
        }
    })()

第一种解决方案利用使用的 catch 方法,第二种解决方案使用 try catch 以上两种方法都可以解决,但是不够优雅,因为当有多个异步操作时需要写成:
方案一:

	(async () => {
		const resA = await request(false).catch(errA => console.log('errA', errA))
		const resB = await request(false).catch(errB => console.log('errB', errB))
		const resC = await request(false).catch(errC => console.log('errC', errC))
		// ...
	})()

方案二(1):

	(async () => {
		try {
			const resA = await request(false)
		} catch(errA) {
			// ...错误处理
			console.log('errA', errA)
		}
		try {
			const resB = await request(false)
		} catch(errB) {
			// ...错误处理
			console.log('errB', errB)
		}
		try {
			const resC = await request(false)
		} catch(errC) {
			// ...错误处理
			console.log('errC', errC)
		}
		try {	
			// ...
		} catch(errX) {}
	})()

方案二(2):

    (async () => {
        try {
            const resA = await request(false)
            const resB = await request(false)
            const resC = await request(false)
        } catch(err) {
            if (err.type === 'errA') {
				// 错误处理
			} else if (err.type === 'errB') {
				// 错误处理
			}
        }
    })()

以上两种方案在异步处理数量多的情况下,会显得更加复杂,似乎对不起语法糖这个称号。有没有一种方法可以优雅处理 async/await 中的错误? 答案是有的。

	 // 抽离成公共方法
    const awaitWrap = promise => {
        return promise
            .then(res => [null, res])
            .catch(err => [err, null])
    }
	(async () => {
		const [err, res] = await awaitWarp(request(false))
		console.log('res', res)   	 // null
		console.log('err', err)		 // err fail
	})()
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在使用async/await进行异步编程时,可以通过try...catch语句来捕获错误。这种方式可以在try块执行可能导致错误发生的代码,然后在catch块处理错误情况。在catch块,我们可以根据具体的错误类型进行相应的处理操作。 另一种方式是使用awaitWraper函数封装异步函数调用,该函数可以将错误和正确的返回值进行区分。通过使用awaitWraper函数,我们可以避免每次都写冗余的错误处理代码,从而使代码更简洁和优雅。在使用这种方式时,我们可以通过解构赋值来获取错误和返回值,然后根据需要进行处理。 总之,无论是使用try...catch语句还是封装成工具函数,都可以实现async/await错误捕获和处理,让异步编程更加可靠和健壮。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [async/await错误捕获](https://blog.csdn.net/qq_39970857/article/details/116979564)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [async/await错误捕获](https://blog.csdn.net/Amnesiac666/article/details/123104855)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值