当前位置:网站首页>如何优雅的处理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();
总结
不管你用什么方式都可用,看你喜欢什么风格的编码方式
此篇文章只是提供更多的方式来解决实际开发中的问题
如果你有更好的方式欢迎留言评论
边栏推荐
- Gets or sets the content in an object
- 记录一次排查问题的经过——视频通话无法接起
- Answer private message @ Tiantian Wx //2022-6-12 C language 51 single chip microcomputer led analog traffic light
- Common ways to traverse map sets
- 【剑指Offer】面试题25.合并两个有序的链表
- 第007天:go语言字符串
- Analysis of the implementation principle of an open source markdown to rich text editor
- Message scrolling JS implementation
- MySQL索引
- Redis hyperloglog cardinality statistics algorithm
猜你喜欢

Call C function in Lua

【Flutter 問題系列第 67 篇】在 Flutter 中使用 Get 插件在 Dialog 彈窗中不能二次跳轉路由問題的解决方案

Ultra quicksort reverse sequence pair

1.4.2 Capital Market Theroy

Uni app Ali font icon does not display

Day 007: go language string

CTFSHOW SQL注入篇(211-230)

Hugo 博客搭建教程

Small program input element moving up

Common encryption and decryption function encapsulation - AES encryption and decryption
随机推荐
Analyse du principe de mise en œuvre d'un éditeur de texte open source markdown - to - rich
Redis
Ladder race
Zoom and move the H5 part of the mobile end
Redis
Common encryption and decryption function encapsulation - AES encryption and decryption
Sword finger offer 56 - I. number of occurrences in the array
Alipay native components (hotel time selection)
CTFSHOW SQL注入篇(231-253)
1.4.2 Capital Market Theroy
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
SS selector
Ultra quicksort reverse sequence pair
【Flutter 问题系列第 67 篇】在 Flutter 中使用 Get 插件在 Dialog 弹窗中不能二次跳转路由问题的解决方案
Use ASE encryption and decryption cache encapsulation in Vue project
Use the visual studio code terminal to execute the command, and the prompt "because running scripts is prohibited on this system" will give an error
十亿数据量 判断元素是否存在
Knife4j aggregation 2.0.9 supports automatic refresh of routing documents
Notes on software test for programmers -- basic knowledge of software development, operation and maintenance
基于DE2-115平台的VGA显示