当前位置:网站首页>如何优雅的处理async/await错误信息
如何优雅的处理async/await错误信息
2022-06-13 04:23:00 【Lete乐特】
原文: https://blog.imlete.cn/article/async-await-error-handling.html
废话
在实际开发中,用到了一些异步函数或是请求。你可能会写.then()和.catch()来处理异步的成功与失败
那么如果这个.then()里又有一个请求,那么时不时又得写.then()和.catch(),那么很有可能.catch()里也有呢?
这里就不多说什么回调地狱的问题了
你可能就会用async和await来处理异步请求,但这也就会随着产生一个问题,那就是await它无法捕获异步请求的错误啊
这时你又想到,那我包一层try...catch不就好了吗?
但是这仅仅只能处理当前这个方法的错误,如果这个方法里又多个请求或者说是其他同步代码产生的问题,错误也只能定位到这个方法。try...catch对代码的可读性不是很友好(个人觉得)
如果你觉得上面所说的,你觉得很 ok,就是要用上面说的
try...catch还是.then()和.catch(),就随便你
萝卜青菜,各有所爱(你想用啥就用啥)
正文
现在有如下代码:
// 成功
function Success() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Run Success");
}, 500);
});
}
// 失败
function UnSuccess() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Run Error"));
}, 500);
});
}
async function run() {
console.log("start");
const result = await Success();
console.log("result:", result);
console.log("end");
}
run();
then-catch
用.then()和.catch()来处理
async function run() {
console.log("start");
UnSuccess()
.then((res) => {
console.log("result:", res);
})
.catch((err) => {
console.log("发生了错误!");
console.log(err);
})
.then(() => {
console.log("end");
});
}
try-catch
用try...catch来处理
async function run() {
try {
console.log("start");
const result = await UnSuccess();
console.log("result:", result);
} catch (err) {
console.log("发生了错误!");
console.log(err);
}
console.log("end");
}
run();
then-catch 结构赋值
.then()和.catch()联合结构赋值来处理
这种方式仅仅是简化了
.then()和.catch()方式而已
async function run() {
console.log("start");
const [err, result] = await UnSuccess()
.then((result) => [null, result])
.catch((err) => [err, null]);
if (err) {
console.log("发生了错误!");
console.log(err);
return;
}
console.log("result:", result);
console.log("end");
}
run();
封装 then-catch 结构赋值
简单的封装以下就可用在很多地方进行复用了
根前面的代码对比时不时好了很多?
/** * Promise函数错误处理 * @param {Function} asyncFn 这是一个Promise函数 * @returns {Array} [err,result] */
function AsyncHandling(asyncFn) {
return asyncFn()
.then((result) => [null, result])
.catch((err) => [err, null]);
}
async function run() {
console.log("start");
const [err, result] = await AsyncHandling(UnSuccess);
if (err) {
console.log("发生了错误!");
console.log(err);
return;
}
console.log("result:", result);
console.log("end");
}
run();
总结
不管你用什么方式都可用,看你喜欢什么风格的编码方式
此篇文章只是提供更多的方式来解决实际开发中的问题
如果你有更好的方式欢迎留言评论
边栏推荐
- R: Airline customer value analysis practice
- 剑指 Offer 56 - I. 数组中数字出现的次数
- [chapter 67 of the flutter problem series] the solution to the problem that the get plug-in cannot jump to the route twice in the dialog pop-up window in flutter
- 1-72 convert string to decimal integer
- This Sedata uses multiple methods to dynamically modify objects and values in arrays. Object calculation properties
- 小程序基础入门(黑马学习笔记)
- PAT 1054 The Dominant Color
- Knife4j aggregation 2.0.9 supports automatic refresh of routing documents
- dumi 搭建文档型博客
- Ctfshow SQL injection (231-253)
猜你喜欢
![[chapter 67 of the flutter problem series] the solution to the problem that the get plug-in cannot jump to the route twice in the dialog pop-up window in flutter](/img/59/0d95619ee3bba1f8992d90267d45c2.png)
[chapter 67 of the flutter problem series] the solution to the problem that the get plug-in cannot jump to the route twice in the dialog pop-up window in flutter

How to use debounce in lodash to realize anti shake

Sword finger offer II 022 Entry node of a link in a linked list

2022 ICLR | CONTRASTIVE LEARNING OF IMAGE- AND STRUCTURE BASED REPRESENTATIONS IN DRUG DISCOVERY

EMC整改纲要

Hugo blog building tutorial

Ctfshow SQL injection (231-253)

Uni app dynamic add style dynamic bind background image invalid

Small program imitating Taobao Jiugong grid sliding effect

一款开源的Markdown转富文本编辑器的实现原理剖析
随机推荐
Dumi construit un blog documentaire
H5 the blue background color appears when clicking the picture
How to use debounce in lodash to realize anti shake
Uni app enables pull-up loading and pull-down refresh (pull-down with animation)
Mongodb compass connects to the Alibaba cloud remote server database or reports an error occurred while loading instance info: command hostinfo req
剑指 Offer 56 - I. 数组中数字出现的次数
Clear timer failure
JS common array methods
Lenovo notebook computer uses the insert key. When the mouse becomes a small square, how to solve it
[sword finger offer] interview question 24 Reverse linked list
Common terms of electromagnetic compatibility
The most detailed swing transformer mask of window attachment in history -- Shaoshuai
1.4.2 Capital Market Theroy
10 minutes to thoroughly understand how to configure sub domain names to deploy multiple projects
CTFSHOW 常用姿势篇(821-830)
[flutter problem Series Chapter 67] the Solution to the problem of Routing cannot be jumped again in in dialog popup Using get plug - in in flutter
Real time question answering of single chip microcomputer / embedded system
Use ASE encryption and decryption cache encapsulation in Vue project
Webpack system learning (VIII) how contenthash can prevent browsers from using cache files
【剑指Offer】面试题24.反转链表