【Js】不使用try catch,优雅地处理await报错的情况
文章目录
const res = await jiekou(params);
if(res.code === 0) {
//执行代码
} else {
// 错误处理
}类似场景景:如果jiekou报500,那不会走到下面的if判断,那相应的代码都不会执行。
解决方式:
// 写一个方法去执行原本的操作,如果有错误返回[err],没有错误返回[null, res]
function getAwaitResult(promise) {
return promise.then(res => {
return [null, res];
})
.catch(err => [err]);
}使用
const [err, res] = await getAwaitResult(jiekou(params));
if (err) {
// 例如此处需要不显示loading
this.loading = false;
this.$message.error(String(err));
return;
}
// 后面执行res的正常操作就好
if (res.code === 0) {
this.imageList = res.data.list;
this.total = res.data.total;
} else {
this.$message.error(res.msg);
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论