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

*【序】(本文章主要是学习性质,对[原文](https://www.jianshu.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(

promise: Promise,

errorExt?: object

): Promise {

return promise

.then((data: T) => [null, data])

.catch(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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值