废话
在实际开发中,用到了一些异步函数或是请求。你可能会写.then()和.catch()来处理异步的成功与失败
那么如果这个.then()里又有一个请求,那么时不时又得写.then()和.catch(),那么很有可能.catch()里也有呢?
这里就不多说什么回调地狱的问题了
你可能就会用async和await来处理异步请求,但这也就会随着产生一个问题,那就是await它无法捕获异步请求的错误啊
这时你又想到,那我包一层try...catch不就好了吗?
但是这仅仅只能处理当前这个方法的错误,如果这个方法里又多个请求或者说是其他同步代码产生的问题,错误也只能定位到这个方法。
try...catch对代码的可读性不是很友好(个人觉得)
如果你觉得上面所说的,你觉得很 ok,就是要用上面说的try...catch还是.then()和.catch(),就随便你
萝卜青菜,各有所爱(你想用啥就用啥)
正文
现在有如下代码:
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   |  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()来处理
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | 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来处理
    
    1 2 3 4 5 6 7 8 9 10 11 12
   | 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()方式而已
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | 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 结构赋值
简单的封装以下就可用在很多地方进行复用了
根前面的代码对比时不时好了很多?
    
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | 
 
 
 
  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();
 
  | 
 总结
不管你用什么方式都可用,看你喜欢什么风格的编码方式
此篇文章只是提供更多的方式来解决实际开发中的问题
如果你有更好的方式欢迎留言评论