js优雅的解决async/await函数的报错

*【序】(本文章主要是学习性质,对[原文](//www.greatytc.com/p/2935c0330dd2)的二次精简和记录)今天要处理一个async/await中的错误,平时都是使用try/catch,突然想找找看是否有更优雅的方式,确实又学习到了不少,

问题一

  • 【疑惑】当我们在async函数中去处理错误时,正常都用try/catch,但是try/catch的嵌套另前端工程师颇为蛋疼,如下代码
async function asyncFunc() {
    try {
        const product = await Api.product({ id : 10 });
        if(!product) {
            console.log('No product found');
        }
    }
    catch(err) {
        console.log(err);
    }

    try {
        const saveProduct = await Api.save({
            id: product.id,
            name: product.name
        });
    }
    catch(err) {
        console.log(err);
    }

}

是否有一种更优雅的解决办法?

  • 【解惑】 github上有一个项目await-to-js,可以用promise来替代try/catch
  • 【关键】代码短小但用处很大
export function to<T, U = any>(
  promise: Promise<T>,
  errorExt?: object
): Promise<[U | null, T | undefined]> {
  return promise
    .then<[null, T]>((data: T) => [null, data])
    .catch<[U, undefined]>(err => {
      if (errorExt) {
        Object.assign(err, errorExt)
      }

      return [err, undefined]
    })
}

export default to

调用的效果

import to from './to.js';

async function asyncFunc() {
    let err, product, saveProduct;

    [err, product] = await to(Api.product({ id : 10 }));
    if(!product) {
        console.log('No product found');
    }

    [err, saveProduct] = await to(Api.save({
        id: product.id,
        name: product.name
    }));

    if(err) {
        console.log(err);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。